Closed Captioning Closed captioning available on our YouTube channel

How to use the OR operator: 2-Minute Linux Tips

Network World | Jun 5, 2020

In this Linux tip, learn how to use the OR (||) operator that provides a useful functionality in scripts. But, first, to demonstrate how this operator works, we’ll run a couple simple commands on the command line.

Copyright © 2020 IDG Communications, Inc.

Similar
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 OR (||) operator that provides a useful functionality in scripts. But, first, to demonstrate how this operator works, we’ll run a couple simple commands on the command line.
In that command, if we are able to add text to myfile, the second echo command won’t be run.
Here’s another example:
In this example, the contents of myfile are displayed if the file is available. If not, the command tries to create it. Think of || as specifying “Run the first command. If it succeeds, you’re done. If it fails, run the second command”. Display the file OR create it.
The || operator is most often used in scripts when you need to take some action if some condition isn’t met. For example, you might have a line like this in a script:
In other words, we try to look at the bottom lines in testfile, but issue an error message and exit the script if the file doesn’t exist or can’t be read.
In this last example, we test values that need to be a strings of digits and exit with an error code if either value doesn’t match that form.
That’s your Linux tip for using the OR (||) operator.
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.
Popular
Featured videos from IDG.tv