Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash:传递复合命令_Bash - Fatal编程技术网

Bash:传递复合命令

Bash:传递复合命令,bash,Bash,我有一个名为inDir的Bash函数,它抽象了转到一个目录,做一些事情,然后返回到起始目录模式。其定义如下: inDir() { if [ $# -gt 1 ]; then local dir="$1" local cwd=`pwd` shift if [ -d "$dir" ]; then cd "$dir" && "$@" cd "$cwd"

我有一个名为inDir的Bash函数,它抽象了转到一个目录,做一些事情,然后返回到起始目录模式。其定义如下:

inDir() {
    if [ $# -gt 1 ]; then
        local dir="$1"
        local cwd=`pwd`
        shift

        if [ -d "$dir" ]; then
            cd "$dir" && "$@"
            cd "$cwd"
        fi
    fi
}
我试图创建一个语义无关紧要的函数,但它基本上可以运行:

inDir /tmp { [ -e testFile ] && touch testFile }
我希望隐含的语义是清楚的。我想进入一个目录,检查$somefile是否存在,如果存在,删除它。这不符合预期。如果我跑步:

cd
inDir /tmp [ -e testFile ] && touch testFile

它检查testFile是否存在于/tmp中,然后尝试在~。有人能想出一个调用inDir的好方法,让它接受复合命令吗?

没有。告诉它调用一个子shell

inDir /tmp bash -c "[ -e testFile ] && touch testFile"

没有。告诉它调用一个子shell

inDir /tmp bash -c "[ -e testFile ] && touch testFile"

你不使用pushd和popd有什么特别的原因吗?@sarnold:把它扔进一个子shell,你甚至不需要这样做popd@Seth哈,又好又懒我一直在避免子shell,因为我希望能够看到处理的结果。例如,inDir的一些用法调用wget。pushd和popd是确定的可能性。子shell不会隐藏任何内容,当您谈论list时,它实际上是一个子shell环境,实际上不会分叉任何内容。当您离开paren时,它只会隐式地放弃变量分配、目录更改和其他shell状态更改。您不使用pushd和popd有什么特殊原因吗?@sarnold:将其放入子shell,您甚至不需要这样做popd@Seth哈,又好又懒我一直在避免子shell,因为我希望能够看到处理的结果。例如,inDir的一些用法调用wget。pushd和popd是确定的可能性。子shell不会隐藏任何内容,当您谈论list时,它实际上是一个子shell环境,实际上不会分叉任何内容。当您离开paren时,它只会隐式地放弃变量分配、目录更改和其他shell状态更改。