Here is the video version, if you prefer it:
Let’s talk about logical operators outside of the context of shell scripts, at first.
If I run two commands like this:
touch someFile && emacs someFile
what would happen is that I would create a file named someFile
and then I would immediately open it with Emacs (if you don’t have Emacs, you can use less). However, try this:
mislav@mislavovo-racunalo:~/Linux_folder$ ls -l nonExistentFile && emacs someFile
ls: cannot access 'nonExistentFile': No such file or directory
What happened here is that we tried to use ls
on a non existent file and we got an error message. But our Emacs didn’t open up as well. What is happening here?
See, when you use the &&
operator (also known as the “and” operator) you are saying “Execute the first command and then, if it succeeds, execute the second command”. How does the shell know if a command executed successfully? Why, by exit code, of course! (Ward, 2014)
When a command is successful, its exit code is 0. &&
says “I will execute the second command only if the exit code of the first command (to the left of the &&
sign) is 0”. ||
, another logical operator, says just the opposite: “I will execute the second command only if the exit code of the first command (to the left of the ||
sign) is not 0”. You can remember it like this, but this makes more sense if you know about logical gates, which you don’t need to to understand Linux, so I won’t explain those.
So if I write:
mislav@mislavovo-racunalo:~/Linux_folder$ ls -l nonExistentFile || emacs someFile
this actually opens up Emacs, because ||
works in the way I described above.
Hope you learned something useful!
References
Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Page 258
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.