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

跟風遠走 提交于 2019-11-30 12:24:08

Set a trap on ERR:

#!/bin/bash

err=0
trap 'err=1' ERR

command1
command2
command3
test $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/bash
for i in 1 2 3; do
        eval "command$i() { echo command$i; test $i != 2; }"
done

err=0
report() {
        err=1
        echo -n "error at line ${BASH_LINENO[0]}, in call to "
        sed -n ${BASH_LINENO[0]}p $0
} >&2
trap report ERR

command1
command2
command3
exit $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:

#!/bin/bash

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

true
false
true

echo "Errors: $errcount"

returns Errors: 1 and

#!/bin/bash

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

true
false
true
false

echo "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.

codeforester

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 command1
run_cmd_with_check command2
run_cmd_with_check command3
printf "$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

You have the magic variable $? available in bash which tells the exit code of last command:

#!/bin/bash

command1  # exits with status 1
C1_output=$?   # will be 1
command2  # exits with status 0
C2_output=$?   # will be 0
command3  # exits with status 0
C3_output=$?   # will be 0

For each command you could do this:

if ! Command1 ; then an_error=1; fi 

And repeat this for all commands

At the end an_error will be 1 if any of them failed.

If you want a count of failures set an_error to 0 at the beginning and do $((an_error++)). Instead of an_error=1

You could place your list of commands into an array and then loop over the commands. Any that return an error code your keep the results for later viewing.

declare -A results

commands=("your" "commands")

for cmd in "${commands[@]}"; do 
    out=$($cmd 2>&1)
    [[ $? -eq 0 ]] || results[$cmd]="$out"
done    

Then to see any non zero exit codes:

for cmd in "${!results[@]}"; do echo "$cmd = ${results[$cmd]}"; done

If the length of results is 0, there were no errors on your list of commands.

This requires Bash 4+ (for the associative array)

You can use the DEBUG trap like:

trap 'code+=$?' DEBUG
code=0

# run commands here normally

exit $code
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!