OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Control Operators: Another Way To Branch

bash provides two control operators that can perform branching. The && (AND) and || (OR) operators work like the logical operators in the [[ ]] compound command. This is the syntax:

command1 && command2

and

command1 || command2

It is important to understand the behavior of these. With the && operator, command1 is executed and command2 is executed if, and only if, command1 is successful. With the || operator, command1 is executed and command2 is executed if, and only if, command1 is unsuccessful.

In practical terms, it means that we can do something like this:



[me@linuxbox ~]$ mkdir temp && cd temp

[me@linuxbox ~]$ mkdir temp && cd temp


This will create a directory named temp, and if it succeeds, the current working directory will be changed to temp. The second command is attempted only if the mkdir com- mand is successful. Likewise, a command like this:



[me@linuxbox ~]$ [[ -d temp ]] || mkdir temp

[me@linuxbox ~]$ [[ -d temp ]] || mkdir temp


will test for the existence of the directory temp, and only if the test fails, will the direc- tory be created. This type of construct is very handy for handling errors in scripts, a sub- ject we will discuss more in later chapters. For example, we could do this in a script:


[ -d temp ] || exit 1

[ -d temp ] || exit 1


If the script requires the directory temp, and it does not exist, then the script will termi- nate with an exit status of one.


Top OS Cloud Computing at OnWorks: