Friday, April 26, 2013

Logical AND and OR in bash

In bash (bourne again shell), the logical operand AND and OR are being symbolized by && and ||. The usage example are as follow:

&& ( If first command succeed, continue with second command, else stop )

$ ls 
cat  lion  tiger

$ ls cat && echo "there is cat"
cat
there is cat
 
$ ls elephant && echo "there is elephant"
ls: cannot access elephant: No such file or directory


You can see from above that command `echo "there is elephant"` did not get executed because the command `ls elephant` did not successfully finish (non zero exit code)


|| ( If  the first command failed, execute second command, else stop )

$ ls 
cat  lion  tiger

$ ls cat || echo "there is no cat"
cat

$ ls elephant || echo "there is no elephant"
ls: cannot access elephant: No such file or directory
there is no elephant


Now you can see that, if the first command returned non zero exit code (failed), the second command will be executed.

To run the second command, while ignoring the first command's result, use ";" instead:

$ ls tiger; echo "there is tiger"
tiger
there is tiger

$ ls elephant; echo "there is no elephant"
ls: cannot access elephant: No such file or directory
there is no elephant


That's all folks.





No comments: