加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 18:43:08 所属栏目:安全 来源:网络整理
导读:我目前使用这个函数来包装执行命令并记录其执行,并返回代码,并在非零返回码的情况下退出. 然而,这是有问题的,因为显然,它做双重内插,使命令与单引号或双引号在其中打破脚本. 你能推荐一个更好的方法吗? 这是功能: do_cmd(){ eval $* if [[ $? -eq 0 ]] the
我目前使用这个函数来包装执行命令并记录其执行,并返回代码,并在非零返回码的情况下退出.

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

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

这是功能:

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读