Almost all programming languages provide an if statement for controlling the flow of a program based upon the result of a test. This simple example illustrates one acceptable format of the UNIX shell's if statement: |
if [ -f unixfile ] |
This snippet of code will remove (delete) the file named unixfile if it exists and is a regular file. The -f enclosed within brackets performs this test. These two UNIX commands, the -f test and the remove statement, can be combined and compacted into a single line of code by using the && shell construct: |
[ -f unixfile ] && rm unixfile |
This statement is read, if command1 is true (has an exit status of zero) then perform command2. |
command1 || command 2 |
If the exit status of command1 is false (non-zero), command2 will be executed. |
if [ -f unixfile ] |
Using && and || together, this block of code can be reduced to: |
[ -f unixfile ] && rm unixfile || print "unixfile was not found, or is not a regular file" |
Finally, multiple commands can be executed based on the result of command1 by incorporating braces and semi-colons: |
command1 && { command2 ; command3 ; command4 ; } |
If the exit status of command1 is true (zero), commands 2, 3, and 4 will be performed. |
These two UNIXshell constructs are very powerful tools for any shell script programmer'sarsenal.