bash – 最好的方法是编写一个运行命令并记录其退出代码的包装函数

前端之家收集整理的这篇文章主要介绍了bash – 最好的方法是编写一个运行命令并记录其退出代码的包装函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前使用这个函数来包装执行命令并记录其执行,并返回代码,并在非零返回码的情况下退出.

然而,这是有问题的,因为显然,它做双重内插,使命令与单引号或双引号在其中打破脚本.

你能推荐一个更好的方法吗?

这是功能

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
}

猜你在找的Bash相关文章