Exploiting the shell’s capabilities can be fun and very helpful. Using the shell, I’ll often want to chain commands together. While you may already be familiar with using the semicolon to call commands in the order they were typed on the command line, the shell provides two “constructs” that permit some related, yet very specific behaviors. These constructs are more powerful than simply running commands in a sequence. They allow us to perform a command based on the success or failure of the prior command, and they’re both very easy to use.
The first construct is the double ampersand, &&. When combined with commands on both sides of the double ampersand, the second command will only be executed if the first command was successful. For example, I’ll often execute something like this:
nice unrar e mymoviebackup.rar && rm mymoviebackup.rar
This will delete the original archive, but only if the extraction was successful. On the converse, I may want a command to execute, but only if the first previous command failed. Using the double pipe to separate two commands allows me to do just that.For example,
cp mysysbackup.tar /media/usbdisk1/mytapebackup.tar || touch ~/Desktop/BackupFailed
The above commands works like this : If the copying of mysysbackup.tar to my external drive fails, create or update a file on my desktop that advises me of the failure.
Save This Page

Post a Comment
You must be logged in to post a comment.