Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

In bash, I sometimes want to run several commands in serial and don't want to wait for them to finish before I type the new ones. So I do something like this:

cmd1; cmd2; cmd3

Unfortunately, one of the commands might fail. In that case, I'd like to stop. Is there an easy way to do this, but make it so that I only keep running the commands if the previous command had a 0 exit code?

share|improve this question
add comment

3 Answers

up vote 30 down vote accepted

Use && operator,

cmd1 && cmd2 && cmd3

In shellscripting, && and || operators are modelled after optimized implementation of logical operators in C. && means AND operator, and || means OR. The key point is that in C, the second operand of these operators isn't evaluated if the result is already known from the first operand. E.g. "false && x" is false for any x, so there is no need to evaluate x; similarly for "true || x".

And in Unix, it is traditional to interpret commands' return values as "successful completion" truth values: exit code 0 means true (success), nonzero means false (failure). So, when the first command in cmd1 && cmd2 returns "false" (nonzero exit status, which indicates failure), the compound command's status is known: failure. So overall interpretation of cmd1 && cmd2 may be: "execute cmd1, AND THEN, if it didn't fail, cmd2". Which is what you basically want in your question.

Similarly with OR: cmd1 || cmd2 can be interpreted as "execute cmd1, OR IF it fails, cmd2".

share|improve this answer
    
+1 for explaining || –  Alp Jun 23 '13 at 13:47
add comment

Simply with the && operator. For instance:

cmd1 && cmd2 && cmd3

If one of the commands fails (returns an exit value other than 0), the other commands won't run.

share|improve this answer
add comment

"Chaining Commands an grouping them"

ping 192.168.0.1 || { echo "ping not successful"; exit 1; }

pings, only if not successful, executes the chained group of commands in brackets.

Attention:

The list has to be terminated with a ";".

There must be blank spaces between brackets and the grouped commands!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.