什么是写运行命令并记录他们的退出code的包装功能的最佳途径 [英] What is the best way to write a wrapper function that runs commands and logs their exit code
问题描述
我目前使用此功能包执行命令并记录它们的执行,并返回code,并以非零返回code的情况下退出。
然而,这只是问题的,因为很显然,它双插,使得它们与单或双引号的命令打破脚本。
你能推荐一个更好的办法?
下面的功能:
do_cmd()
{
EVAL $ *
如果[[$? -eq 0]
然后
回声成功运行[$ 1]
其他
回声错误:命令[$ 1]返回$?
退出$?
科幻
}
$ @
http://www.gnu.org/software /bash/manual/bashref.html#Special-Parameters :
@
扩展为位置参数,从1开始。当。。。的时候
双引号里展开时,每个参数扩展到一个
单独的字。也就是说,$ @等同于$ 1,2 $....如果
双引号的扩展一个字内发生,对扩大
第一参数接合与原来的开始部分
字,并在最后一个参数的膨胀接合与最后
原始单词的一部分。当有没有位置参数,
$ @和$ @扩大到什么(即,它们被删除)。
块引用>这是指在参数空间重新正确引用。
do_cmd()
{
$ @
RET = $?
如果[[$沤-eq 0]
然后
回声成功运行[$ @]
其他
回声错误:命令[$ @]返回$ RET
退出$沤
科幻
}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 [ $1 ]" else echo "Error: Command [ $1 ] returned $?" exit $? fi }
解决方案"$@"
From 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).
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 }
这篇关于什么是写运行命令并记录他们的退出code的包装功能的最佳途径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!