How to tell if any command in bash script failed (non-zero exit status) How to tell if any command in bash script failed (non-zero exit status) bash bash

How to tell if any command in bash script failed (non-zero exit status)


Set a trap on ERR:

#!/bin/basherr=0trap 'err=1' ERRcommand1command2command3test $err = 0 # Return non-zero if any command failed

You might even throw in a little introspection to get data about where the error occurred:

#!/bin/bashfor i in 1 2 3; do        eval "command$i() { echo command$i; test $i != 2; }"doneerr=0report() {        err=1        echo -n "error at line ${BASH_LINENO[0]}, in call to "        sed -n ${BASH_LINENO[0]}p $0} >&2trap report ERRcommand1command2command3exit $err


You could try to do something with a trap for the DEBUG pseudosignal, such as

trap '(( $? && ++errcount ))' DEBUG

The DEBUG trap is executed

before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function

(quote from manual).

So if you add this trap and as the last command something to print the error count, you get the proper value:

#!/usr/bin/env bashtrap '(( $? && ++errcount ))' DEBUGtruefalsetrueecho "Errors: $errcount"

returns Errors: 1 and

#!/usr/bin/env bashtrap '(( $? && ++errcount ))' DEBUGtruefalsetruefalseecho "Errors: $errcount"

prints Errors: 2. Beware that that last statement is actually required to account for the second false because the trap is executed before the commands, so the exit status for the second false is only checked when the trap for the echo line is executed.


I am not sure if there is a ready-made solution for your requirement. I would write a function like this:

function run_cmd_with_check() {  "$@"  [[ $? -ne 0 ]] && ((non_zero++))}

Then, use the function to run all the commands that need tracking:

run_cmd_with_check command1run_cmd_with_check command2run_cmd_with_check command3printf "$non_zero commands exited with non-zero exit code\n"

If required, the function can be enhanced to store all failed commands in an array which can be printed out at the end.


You may want to take a look at this post for more info: Error handling in Bash