我目前使用这个函数来包装执行命令并记录其执行,并返回代码,并在非零返回码的情况下退出.
然而,这是有问题的,因为显然,它做双重内插,使命令与单引号或双引号在其中打破脚本.
你能推荐一个更好的方法吗?
这是功能:
do_cmd() { eval $* if [[ $? -eq 0 ]] then echo "Successfully ran [ $1 ]" else echo "Error: Command [ $1 ] returned $?" exit $? fi }
"$@"
从http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters:
@
Expands to the positional parameters,starting from one. When the
expansion occurs within double quotes,each parameter expands to a
separate word. That is,“$@” is equivalent to “$1” “$2” …. If the
double-quoted expansion occurs within a word,the expansion of the
first parameter is joined with the beginning part of the original
word,and the expansion of the last parameter is joined with the last
part of the original word. When there are no positional parameters,
“$@” and $@ expand to nothing (i.e.,they are removed).
这意味着参数中的空格被正确地引用.
do_cmd() { "$@" ret=$? if [[ $ret -eq 0 ]] then echo "Successfully ran [ $@ ]" else echo "Error: Command [ $@ ] returned $ret" exit $ret fi }