2011-05-20 114 views
1

我有一个名为“inDir”的Bash函数,它抽象出“转到目录,执行某些操作并返回到起始目录”模式。它被定义为:Bash:传递复合命令

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

     if [ -d "$dir" ]; then 
      cd "$dir" && "[email protected]" 
      cd "$cwd" 
     fi 
    fi 
} 

我想创建,其语义奈何不了的功能,但将主要运行:

inDir /tmp { [ -e testFile ] && touch testFile } 

我希望“隐含”的语义是明确的。我想进入一个目录,检查$ somefile是否存在,如果存在,删除它。这不符合预期。如果我运行:

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

它检查testFile是否存在于/ tmp中,然后尝试在〜中触摸它。任何人都可以想出一个调用inDir的好方法,以便它接受“复合”命令?

+0

你没有使用'pushd'和'popd'有什么特别的原因吗? – sarnold 2011-05-20 23:09:02

+0

@sarnold:扔在一个子壳中,你甚至不需要popd – 2011-05-20 23:15:08

+0

@Seth,哈,好,懒。 :) – sarnold 2011-05-20 23:30:20

回答

3
indir() { 
if [ -d "$1" ]; then 
    local dir="$1" 
    shift 
    (cd "$dir" && eval "[email protected]") 
fi 
} 

indir /tmp touch testFile 
indir /tmp "[ -e testFile ] && rm testFile" 
+0

很好,谢谢。 – nomen 2011-05-20 23:23:27

2

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

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