Get exit code from last channel (stdin)

I would like to be able to create a bash function that can read the exit code of a command before a pipe. I'm not sure if there is access to this.

  • echo "1" | grep 2

    returns 1 status code
  • echo "1" | grep 1

    returns status code 0

Now I would like to add a third command to read the state using a pipe:

  • echo "1" | grep 2 | echo $?

    will echo "0" even if the status code is 1.

I know I can use it echo "1" | grep 2 && echo "0" || echo "1"

, but I would rather write it using a pipe.

They will do it anyway (it would be even better if it worked on most shells like bash, sh and zsh)

+3


source to share


2 answers


You will need to get the exit status before the next stage in the pipeline. Something like

exec 3> debug.txt
{ echo "1"; echo "$?" >&3; } | long | command | here

      

You cannot (easily) encapsulate this in a function, as it would require passing in a properly quoted string and executing it with eval

:



debug () {
    eval "$@"
    echo $? >&3
}

# It looks easy in this example, but it won't take long to find
# an example that breaks it.
debug echo 1 | long | command | here

      

You must write the exit status to another file descriptor, otherwise it will interfere with the output sent to the next command in the pipeline.

+3


source


In bash, you can do this with a variable PIPESTATUS



echo "1" | grep 1
echo ${PIPESTATUS[0]} # returns 0
echo "1" | grep 2
echo ${PIPESTATUS[0]} # returns 0
echo "1" | grep 2
echo ${PIPESTATUS[1]} # returns 1

      

+1


source







All Articles