Thursday, April 16, 2009

Conditional execution && and || in shell script

In shell script, conditional operator && (which is AND) and || (which is OR) is sometimes effective and good for condition checking. Both of their functions and usage are given below.

The usage syntax of && is as simple as,
command 1 && command 2

With this expression at first command 1 is executed. If it is successful which means if exit status of command 1 is zero then command 2 is executed, otherwise command 2 is never executed. We can define this like below.
"Command2 is executed if, and only if, command1 returns an exit status of zero."

The usage syntax of || is also simple like,
command 1 || command 2

With this expression at first command 1 is executed. If it is not successful which means if exit status of command 1 is non-zero only then command 2 is executed, otherwise command 2 is never executed. We can define this like below.
"Command2 is executed if, and only if, command1 returns an exit status of non-zero."

Both of && and || control operator can be combined together inside shell script.
Like,

command1 && command2 ||command3

means if command1 and command2 both are successful then command3 is not executed.
if command1 is unsuccessful then command2 is not executed but command3 is executed.

A fine example of this scenario is trying to delete a file from linux and display message based on that.

# touch test.sh

# rm test.sh && echo "File is deleted" ||echo "File can't be deleted"
rm: remove regular empty file `test.sh'? y
File is deleted

# rm test.sh && echo "File is deleted" ||echo "File can't be deleted"
rm: cannot lstat `test.sh': No such file or directory
File can't be deleted
Related Documents

No comments:

Post a Comment