sh Error Handling

Return Codes

You can see the return code of the last command run with...

echo $?

In your own scripts you can set the return code (to 1 in this case) using...

exit 1

For examples on conditional processing based on return status of a command.

Pipeline Return Codes

When you "pipe" the output of one command to another command, $? only shows the return code of the last command in the pipeline. To see the return codes for all steps in the pipeline you can use a special array variable called ${PIPESTATUS[]}. As demonstrated in the contrived examples below, it is recommended to copy the array to your own array variable if you want to know the value of more than one returncode from the pipeline. This is because once you run a command to handle (in our case "echo") one of the array variables, the returncode of your command overwrites the array)...

The commands true and false are builtin special commands whose only function is to return a 0 (true) or a 1 (false). Handy for boolean logic and for our testing purposes.

false | true | false | true

RC=( "${PIPESTATUS[@]}" )

echo ${RC[0]}

echo ${RC[1]}

echo ${RC[2]}

echo ${RC[3]}

false | true | false | true

echo ${PIPESTATUS[0]}

echo ${PIPESTATUS[1]}

echo ${PIPESTATUS[2]}

echo ${PIPESTATUS[3]}

Note how we only get to see the first returncode, the others are lost once we run "echo".

If you really don't want to populate your own shell array, but still want to know the status of each command in the pipeline, the only alternative is to action all values from a single command. e.g...

false | true | false | true

echo ${PIPESTATUS[@]}

1 0 1 0

If you care whether one of the commands failed in the pipeline but you don't care which one, see the examples below...

false | true | false | true

echo $?

0


set -o pipefail

false | true | false | true

echo $?

1