Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash fail if any single command fails but still run all commands [duplicate]

Tags:

bash

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?

like image 887
Pace Avatar asked Jan 22 '16 16:01

Pace


People also ask

How do I stop a shell script from failing the command?

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.

What is the syntax for executing cmd1 and then if cmd1 fails cmd2?

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.

Which of the following would cause cmd2 to be run only on success of cmd1?

command2 is executed if and only if command1 returns a non-zero exit status.


1 Answers

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.

like image 111
Jonathan Leffler Avatar answered Oct 04 '22 04:10

Jonathan Leffler