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

如何访问eval’d命令的bash PIPESTATUS数组?

发布时间:2020-12-15 21:00:00 所属栏目:安全 来源:网络整理
导读:我有这个代码: error(){ time=$( date +"%T %F" ) echo "Start : ${time} : ${1}" 12 result=$( eval "${1}" ) if [ `echo "${PIPESTATUS[@]}" | tr -s ' ' + | bc` -ne 0 ]; then echo "command ${1} return ERROR" 12 exit else if [ "${2}" != "silent"
我有这个代码:

error(){
    time=$( date +"%T %F" )
    echo "Start : ${time} : ${1}" 1>&2

    result=$( eval "${1}" )
    if [ `echo "${PIPESTATUS[@]}" | tr -s ' ' + | bc` -ne 0 ]; then 
        echo "command ${1} return ERROR" 1>&2
        exit
    else
        if [ "${2}" != "silent" ]; then
          echo "${result}"
        fi
    fi
}

我开始测试命令:

error "ifconfig | wc -l" "silent"
Start : 14:41:53 2014-02-19 : ifconfig | wc -l

error "ifconfiggg | wc -l" "silent"
Start : 14:43:13 2014-02-19 : ifconfiggg | wc -l
./install-streamserver.sh: line 42: ifconfiggg: command not found

但是,我希望得到不同的结果.例:

error "ifconfig" "silent"
Start : 14:44:52 2014-02-19 : ifconfig

Start : 14:45:40 2014-02-19 : ifconfiggg
./install-streamserver.sh: line 42: ifconfiggg: command not found
command ifconfiggg return ERROR  (<<<<<<<<<<<< This message)

我没有它,因为当bash运行带有eval的命令时,就像在

eval "ifconfiggg | wc -l"

$PIPESTATUS [@]数组只包含“0”而不是预期的“1 0”.

我怎样才能解决这个问题?

解决方法

eval启动一个新的shell上下文,它有一个单独的PIPESTATUS []数组.当eval结束时,此上下文的生命周期结束.您可以通过分配给变量(例如PIPE)将??此数组传递给父上下文,如下所示:

$eval 'ifconfiggg | wc -l; PIPE=${PIPESTATUS[@]}'
bash: ifconfiggg: command not found
0
$echo $PIPE
127 0

请注意单引号以防止${PIPESTATUS [@]}过早扩展.

将此包装在另一个结果中= $(…)不起作用,因为这会创建另一个shell上下文.我建议改为一些东西

eval "${1}; "'PIPE=${PIPESTATUS[@]}' >result.out 2>result.err
# do something with $PIPE here
# do something with result.out or result.err here

请注意使用双引号后跟单引号.

(编辑:李大同)

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

    推荐文章
      热点阅读