Probably a simple question but an elegant solution is not coming to mind. I would like to run a series of commands (each one is a test) and return 1 if any of them returned non-zero. Typically I would do something like:
thingA && thingB && thingC
exit $?
However, that won't run thingC if thingB fails and I want to ensure that all 3 run. I can easily think of an inelegant approach:
final_result=0
retval=thingA
if [[ $retval != 0 ]] then
final_result=1
fi
retval=thingB
...
exit $final_result
Is there some simple, elegant way to get what I want?
Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
The pseudo-code in the question does not correspond to the title of the question. If anybody needs to actually know how to run command 2 if command 1 fails, this is a simple explanation: cmd1 || cmd2 : This will run cmd1 , and in case of failure it will run cmd2.
command2 is executed if and only if command1 returns a non-zero exit status.
Is this elegant enough?
status=0
thingA || status=1
thingB || status=1
thingC || status=1
exit $status
You can use $?
instead of 1
if you prefer. Or you could identify the last command that failed by using statuses 1, 2, 3 when you do the assignment. If you wanted to know the first command that failed, you'd have to test $status
before assigning to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With