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

use*_*614 5 bash

我有这个代码:

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
}
Run Code Online (Sandbox Code Playgroud)

我开始测试命令:

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
Run Code Online (Sandbox Code Playgroud)

但是,我期待不同的结果。例子:

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)
Run Code Online (Sandbox Code Playgroud)

我没有它,因为当 bash 使用 eval 运行命令时,如

 eval "ifconfiggg | wc -l"
Run Code Online (Sandbox Code Playgroud)

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

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

Jen*_*ens 3

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

$ eval 'ifconfiggg | wc -l; PIPE=${PIPESTATUS[@]}'
bash: ifconfiggg: command not found
0
$ echo $PIPE
127 0
Run Code Online (Sandbox Code Playgroud)

请注意单引号,以防止${PIPESTATUS[@]}过早展开。

将其包装在另一个中result=$(...)不起作用,因为这会创建另一个 shell 上下文。我建议类似的事情

eval "${1}; "'PIPE=${PIPESTATUS[@]}' >result.out 2>result.err
# do something with $PIPE here
# do something with result.out or result.err here
Run Code Online (Sandbox Code Playgroud)

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