Categories
Linux Tutorial Series

Linux Tutorial Series – 188.1 – Logical operators usage in tests

Here is the video version, if you prefer it:

We talked about logical operators (&& (and) and || (or)) and got to understand how they work. You can also use them in tests.

If you use &&, then if the first test is not successful, its exit code is used for the if statement and if the first test is successful, then the exit code of the second test is used for the if statement. If you use ||, if the first test is not successful, the second test’s exit code is used as the exit code for the if statement and if the first test is successful, the first test’s exit code is used as the exit code for the if statement. (Ward, 2014)⁠

For example, you can write:

if [ “$1” = ‘Hi’ ] || [ “$1” = ‘Hello’ ]

if you were to test if the first argument is either “Hi” or “Hello”.

Think of it like this: && says “Both of the conditions have to be true” while || says “Only one of the conditions must be true”. This holds because only the exit value of 0 is used to indicate success. Re-read the second paragraph and make sure you understand this.

You can combine more than just two conditions with logical operators.

Hope you learned something useful!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Page 258

NewsletterUpdates on interesting things I am doing

Subscribe to my newsletter to keep abreast of the interesting things I'm doing. I will send you the newsletter only when there is something interesting. This means 0% spam, 100% interesting content.

Leave a Reply

Your email address will not be published. Required fields are marked *