Hi, this is Sandra Henry-Stocker, author of the “Unix as a Second Language” blog on NetworkWorld.
In this Linux tip, we’re going to look at the && operator that provides a useful functionality in scripts. But, first, to demonstrate how this operator works, we’ll run some simple commands on the command line.
&& represents an AND operator. For example, if you type this command, both of the echo commands will run because you are asking to have both “hello” AND a welcome message displayed.
If the first command succeeds, the second is run.
In this example, the second command does not run because the first fails – probably because myfile doesn’t exist or we don’t have read privilege. Think of && as specifying “run the first command and, only if it succeeds, run the second command”.
The && operator is most often used in scripts when you need to ensure that some file exists or some other condition is met before you take the next step. For example, you might have a line like this in a script:
In this example, we back up the file if it exists. If it doesn’t, we simply move onto whatever command comes next in the script which probably will create the file from scratch.
In this command, we run a command to delete a file and display a confirming message ONLY if the file exists and is removed. If the file doesn’t exist or we can’t remove it, we squelch the error message by sending its output to /dev/null and never bother with the echo command.
That’s your Linux tip for using &&.
If you have questions or would like to suggest a topic, please add a comment below. And don’t forget to subscribe to the IDG Tech(talk) channel on YouTube.
If you liked this video, please hit the like and share buttons. For more Linux tips, be sure to follow us on Facebook, YouTube and NetworkWorld.com.