bash 编写运行命令并记录其退出代码的包装函数的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/372116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to write a wrapper function that runs commands and logs their exit code
提问by Tom Feiner
I currently use this function to wrap executing commands and logging their execution, and return code, and exiting in case of a non-zero return code.
我目前使用这个函数来包装正在执行的命令并记录它们的执行、返回代码,并在非零返回代码的情况下退出。
However this is problematic as apparently, it does double interpolation, making commands with single or double quotes in them break the script.
然而,这显然是有问题的,它进行双插值,使带有单引号或双引号的命令破坏脚本。
Can you recommend a better way?
你能推荐一个更好的方法吗?
Here's the function:
这是函数:
do_cmd()
{
eval $*
if [[ $? -eq 0 ]]
then
echo "Successfully ran [ ]"
else
echo "Error: Command [ ] returned $?"
exit $?
fi
}
回答by Douglas Leeder
"$@"
From http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters:
来自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).
@
扩展到位置参数,从 1 开始。当扩展发生在双引号内时,每个参数都扩展为一个单独的词。即"$@"等价于"$1" "$2" ....如果双引号扩展发生在一个单词内,则将第一个参数的扩展与原单词的开头部分连接起来,并且最后一个参数的扩展与原始单词的最后一部分相连。当没有位置参数时,"$@" 和 $@ 扩展为空(即,它们被删除)。
This means spaces in the arguments are re-quoted correctly.
这意味着参数中的空格被正确重新引用。
do_cmd()
{
"$@"
ret=$?
if [[ $ret -eq 0 ]]
then
echo "Successfully ran [ $@ ]"
else
echo "Error: Command [ $@ ] returned $ret"
exit $ret
fi
}
回答by Johannes Schaub - litb
Additional to "$@"what Douglas says, i would use
除了"$@"道格拉斯所说的,我会用
return $?
And not exit. It would exit your shell instead of returning from the function. If in cases you want to exit your shell if something went wrong, you can do that in the caller:
而不是exit。它会退出你的 shell 而不是从函数中返回。如果您想在出现问题时退出 shell,您可以在调用者中执行此操作:
do_cmd false i will fail executing || exit
# commands in a row. exit as soon as the first fails
do_cmd one && do_cmd && two && do_cmd three || exit
(That way, you can handle failures and then exit gracefully).
(这样,您可以处理失败,然后优雅地退出)。

