Bash Find out the exit codes of all piped commands

Bash Find out the exit codes of all piped commands

To find out the exit codes of all piped commands in a Bash script, you can use the $PIPESTATUS array.

The $PIPESTATUS array is an array of exit codes for the commands in the most recent pipe. It is updated after each command in the pipe is executed, and its elements correspond to the commands in the order they were executed.

Here is an example of how you can use the $PIPESTATUS array to find out the exit codes of all piped commands:

# Run a pipeline of commands
cmd1 | cmd2 | cmd3

# Print the exit codes of the commands
echo "Exit codes: ${PIPESTATUS[*]}"
Source:w‮l.ww‬autturi.com

This will output the exit codes of the commands cmd1, cmd2, and cmd3, such as Exit codes: 0 0 0.

Note that the $PIPESTATUS array is only updated for the most recent pipe. If you want to find out the exit codes of multiple pipes in a script, you will need to save the exit codes to a separate array or variable after each pipe.

For example:

# Run the first pipe
cmd1 | cmd2 | cmd3
exit_codes_1=(${PIPESTATUS[*]})

# Run the second pipe
cmd4 | cmd5 | cmd6
exit_codes_2=(${PIPESTATUS[*]})

# Print the exit codes
echo "Exit codes for first pipe: ${exit_codes_1[*]}"
echo "Exit codes for second pipe: ${exit_codes_2[*]}"

This will output the exit codes for the first and second pipes separately.

Overall, the $PIPESTATUS array is a useful tool for finding out the exit codes of all piped commands in a Bash script. It allows you to easily track the status of each command in a pipe and perform tasks based on the exit codes.

Created Time:2017-10-27 14:56:34  Author:lautturi