bash pipestatus in backticked command?

后端 未结 3 672
一整个雨季
一整个雨季 2020-12-20 22:56

in bash, if I execute a couple of commands piped together inside of backticks, how can I find out the exit status of the first command?

i.e. in this case, I am tryin

3条回答
  •  悲哀的现实
    2020-12-20 23:42

    The problem is that backticks launch a sub-shell. Your sub-shell has its own ${PIPESTATUS[@]} array, but that does not persist into the parent shell. Here's a trick to shove it into the output variable $a and then retrieve it into a new array called ${PIPESTATUS2[@]}:

    ## PIPESTATUS[0] works to give me the exit status of 'false':
    $ false | true
    $ echo $? ${PIPESTATUS[0]} ${PIPESTATUS[1]}
    0 1 0
    
    ## Populate a $PIPESTATUS2 array:
    $ a=`false | true; printf :%s "${PIPESTATUS[*]}"`
    $ ANS=$?; PIPESTATUS2=(${a##*:})
    $ [ -n "${a%:*}" ] && a="${a%:*}" && a="${a%$'\n'}" || a=""
    $ echo $ANS ${PIPESTATUS2[0]} ${PIPESTATUS2[1]};
    0 1 0
    

    This saves the sub-shell's ${PIPESTATUS[@]} array as a space-delimited list of values at the end of $a and then extracts it using shell variable substring removal (see the longer example and description I gave to this similar question). The third line is only needed if you actually want to save the value of $a without the extra statuses (as if it were run as false | true in this example).

提交回复
热议问题