I want to know whether any commands in a bash script exited with a non-zero status.
I want something similar to set -e
functionality, except that I don't want it to exit when a command exits with a non-zero status. I want it to run the whole script, and then I want to know that either:
a) all commands exited with exit status 0
-or-
b) one or more commands exited with a non-zero status
e.g., given the following:
#!/bin/bash
command1 # exits with status 1
command2 # exits with status 0
command3 # exits with status 0
I want all three commands to run. After running the script, I want an indication that at least one of the commands exited with a non-zero status.
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.
Then to see any non zero exit codes:
If the length of
results
is 0, there were no errors on your list of commands.This requires Bash 4+ (for the associative array)
Set a trap on ERR:
You might even throw in a little introspection to get data about where the error occurred:
I am not sure if there is a ready-made solution for your requirement. I would write a function like this:
Then, use the function to run all the commands that need tracking:
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 can use the
DEBUG
trap like:You have the magic variable
$?
available in bash which tells the exit code of last command:You could try to do something with a trap for the
DEBUG
pseudosignal, such asThe
DEBUG
trap is executed "before every simple command,for
command,case
command,select
command, every arithmeticfor
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:
returns
Errors: 1
andprints
Errors: 2
. Beware that that last statement is actually required to account for the secondfalse
because the trap is executed before the commands, so the exit status for the secondfalse
is only checked when the trap for theecho
line is executed.