- This monster 240W charger has features I've never seen on other accessories (and get $60 off this Black Friday)
- This laptop power bank has served me well for years, and this Black Friday deal slashes the price in half
- This power bank is thinner than your iPhone and this Black Friday deal slashes 27% off the price
- New Levels, New Devils: The Multifaceted Extortion Tactics Keeping Ransomware Alive
- Elden Ring, 2022's Game of the Year, hits a record low price of $20 on Amazon for Black Friday
The logic of && and || on Linux
$ echo hello && echo goodbye hello goodbye
If, on the other hand, the command on the left side fails, the command on the right side is not run. The AND logic (run both commands) simply gives up. The command line just stops with the initial failure. Notice that the “no surprise there” string below is not displayed.
$ cat nosuchfile && echo no surprise there cat: nosuchfile: No such file or directory
Combining || and &&
There’s no reason that you can’t use both || and && operators in a single command. Doing so just makes the parsing a bit trickier. Run a command like this and watch what happens:
$ echo this || echo that && echo the other this the other
The first echo command runs successfully, so the second isn’t run (normal OR behavior). The left side of the AND (&&) was still run successfully, so the right side runs as well.
In the next example, we test whether the /etc/shadow file (the file which holds password encryptions etc.) can be opened for reading. Note the result. The file isn’t opened because the command is not being run with superuser privilege. Note also that error output is being sent to /dev/null so as not to be displayed.
$ cat /etc/shadow 2>/dev/null && echo "file opened" || echo "file failed to open" file failed to open
The failure of opening the /etc/shadow file means the command following the && (AND) is not run. Yet the command following the || (OR) operator is run because, well, that’s the way || works.
Run the command with sudo and you’ll get a different response. Note, though, that I am sending the cat command’s output to /dev/null to avoid stuffing all those lines of output into this post!