UNIX Tutorials, Tips, Tricks and Shell Scripts

Combining UNIX Commands using && and ||


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 ]
then
rm unixfile
fi

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.

The || construct will do the opposite:

command1 || command 2

If the exit status of command1 is false (non-zero), command2 will be executed.

UNIX pipelines may be used on either side of && or ||, and both constructs can be used on the same line to simulate the logic of an if-else statement. Consider the following lines of code:

if [ -f unixfile ]
then
rm unixfile
else
print "unixfile was not found, or is not a regular file"
fi

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 UNIX shell constructs are very powerful tools for any shell script programmer's arsenal.




Do you need to learn UNIX shell scripting and get practice writing & running scripts...on a REAL SERVER? If you are ready to move past the basics, either of these online courses is a good place to start...

UNIX and Linux Operating System Fundamentals contains a very good "Introduction to UNIX Shell Scripting" module, and should be taken if you are new to the UNIX and Linux operating system environments or need a refresher on key concepts.

UNIX Shell Scripting is a good option if you are already comfortable with UNIX or Linux and just need to sharpen your knowledge about shell scripting and the UNIX shell in general.

Both courses include access to an Internet Lab system for completing the course's hands-on exercises, which are used to re-enforce the key concepts presented in the course. Any questions you may have while taking the course are answered by an experienced UNIX technologist.

Thanks for reading, and happy scripting!!!


Has this article been helpful to you? Would it benefit others? If you answered "yes" to either question, kindly share the page.


MORE READERS = MORE FUTURE ARTICLES
Thank you for sharing!