Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiple commands in a bash script sequentially and fail if at least one of them fails

Tags:

bash

I have a bash script that I use to execute multiple commands in sequence and I need to return non-zero exit code if at least one command in the sequence returns non-zero exit code. I know there is a wait command for that but I'm not sure I understand how to use it.

UPD The script looks like this:

#!/bin/bash command1 command2 command3 

All the commands run in foreground. All the commands need to run regardless of which exit status the previous command returned (so it must not behave as "exit on first error"). Basically I need to gather all the exit statuses and return global exit status accordingly.

like image 237
Andrii Yurchuk Avatar asked Apr 18 '13 10:04

Andrii Yurchuk


People also ask

Does bash script execute sequentially?

Yes, they are executed sequentially. However, if you run a program in the background, the next command in your script is executed immediately after the backgrounded command is started.

How do you chain multiple commands in bash?

Ampersand Operator (&) Sixth Bash shell command line Chaining Operator (Linux operator) is Ampersand Operator (&). Ampersand Operator is a kind of operator which executes given commands in the background. You can use this operator to execute multiple commands at once.


1 Answers

Just do it:

EXIT_STATUS=0 command1 || EXIT_STATUS=$? command2 || EXIT_STATUS=$? command3 || EXIT_STATUS=$? exit $EXIT_STATUS 

Not sure which of the statuses it should return if several of commands have failed.

like image 71
kan Avatar answered Oct 02 '22 00:10

kan