How to access the bash PIPESTATUS array of eval'd command?

I have this code:

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
}

I run the testing command:

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

But I expect a different result. Example:

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)

I do not have it, because when bash starts a command with eval, as in

 eval "ifconfiggg | wc -l"

the $ PIPESTATUS [@] array contains only "0" instead of the expected "1 0".

How can i fix this?

+3
source share
1 answer

evallaunches a new shell context that has a separate array PIPESTATUS[]. The lifetime of this context ends when it ends eval. You can pass this array to the parent context by assigning a variable, say, PIPEas follows:

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

, ${PIPESTATUS[@]} .

result=$(...) , . -

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

, .

+3

All Articles