7

我正在研究一个 bash 脚本,如果存在特定文件,我需要有条件地执行一些事情。这种情况多次发生,所以我抽象了以下函数:

function conditional-do {
    if [ -f $1 ]
    then
        echo "Doing stuff"
        $2
    else
        echo "File doesn't exist!"
    end
}

现在,当我想执行此操作时,我会执行以下操作:

function exec-stuff {
    echo "do some command"
    echo "do another command"
}
conditional-do /path/to/file exec-stuff

问题是,我很烦我定义了两件事:一组要执行的命令的函数,然后调用我的第一个函数。

我想以干净的方式将这组命令(通常是 2 个或更多)直接传递给“conditional-do”,但我不知道这是如何实现的(或者是否可能)......有人有吗有任何想法吗?

请注意,我需要它是一个可读的解决方案......否则我宁愿坚持我所拥有的。

4

3 回答 3

6

这对大多数 C 程序员来说应该是可读的:

function file_exists {
  if ( [ -e $1 ] ) then 
    echo "Doing stuff"
  else
    echo "File $1 doesn't exist" 
    false
  fi
}

file_exists filename && (
  echo "Do your stuff..."
)

或单线

file_exists filename && echo "Do your stuff..."

现在,如果您真的希望从函数中运行代码,您可以这样做:

function file_exists {
  if ( [ -e $1 ] ) then 
    echo "Doing stuff"
    shift
    $*
  else
    echo "File $1 doesn't exist" 
    false
  fi
}

file_exists filename echo "Do your stuff..."

不过我不喜欢那个解决方案,因为你最终会转义命令字符串。

编辑:将“eval $*”更改为 $ *。实际上,不需要 Eval。与 bash 脚本一样,它是在我喝了几杯啤酒时编写的;-)

于 2008-09-19T21:59:13.700 回答
0

一种(可能是破解)解决方案是将单独的函数完全存储为单独的脚本。

于 2008-09-19T21:56:27.263 回答
0

正经的回答:

[ -f $filename ] && echo "it has worked!"

或者,如果您真的想要,您可以将其包装起来:

function file-exists {
    [ "$1" ] && [ -f $1 ]
}

file-exists $filename && echo "It has worked"
于 2008-09-21T12:37:53.407 回答