Run a command only if another command returns a zero exit status
Use the
&&
control operator to combine two commands so that the second is run only if the first command returns a zero exit status. In other words, if the first command runs successfully, the second command runs. If the first command fails, the second command does not run at all. For example:Listing 1. Example of good habit #3: Combining commands with control operators
~ $ cd tmp/a/b/c && tar xvf ~/archive.tar |
In this example, the contents of the archive are extracted into the ~/tmp/a/b/c directory unless that directory does not exist. If the directory does not exist, the
tar
command does not run, so nothing is extracted.Run a command only if another command returns a non-zero exit status
Similarly, the
||
control operator separates two commands and runs the second command only if the first command returns a non-zero exit status. In other words, if the first command is successful, the second command does not run. If the first command fails, the second command does run. This operator is often used when testing for whether a given directory exists and, if not, it creates one:Listing 2. Another example of good habit #3: Combining commands with control operators
~ $ cd tmp/a/b/c || mkdir -p tmp/a/b/c |
You can also combine the control operators described in this section. Each works on the last command run:
Listing 3. A combined example of good habit #3: Combining commands with control operators
~ $ cd tmp/a/b/c || mkdir -p tmp/a/b/c && tar xvf -C tmp/a/b/c ~/archive.tar |
No comments:
Post a Comment