Reputation: 1053
Suppose you do following in bash at command prompt:
cmd1;cmd2;cmd3
If cmd1
fails how do you get bash not to do cmd2
.
Upvotes: 2
Views: 671
Reputation: 1283
cmd1 && cmd2 && cmd3
Explanation
Execute cmd1
. If it fails, cmd2
and cmd3
will not be executed.
Why? Because false logically ANDed with anything else is always equal to false, so if cmd1
returns false there is no need to evaluate cmd2
and cmd3
. And by like reasoning, if cmd1
succeeds and cmd2
fails, don't execute cmd3
.
Note
Just to make things a little more confusing, POSIX systems (like Linux and other UNIX variants) return 0 for success and non-zero for failure.
So, when I say failure above
false = non-zero = failure
true = zero = success
Why? Because the numerical value of the return code is used indicate different failure codes.
For example,
$ ls /root
ls: cannot open directory /root: Permission denied
$ echo $?
2
$ asdf
asdf: command not found...
$ echo $?
127
$ ls /
bin boot data dev etc home lib ...
$ echo $?
0
ls
returns "1" for minor problems and "2" for more serious problems. The bash shell returns "127" to indicate "command not found", and ls /
returns "0" to indicate success.
Upvotes: 9