Boolean logical operators, like AND (&&) and OR (||) are somewhat mysterious because Bash
uses them in a variety of ways.
One common use is in command lists, which are chains of commands whose flow is controlled by
operators. The “|” (pipe) symbol is a commonly-used operator in a command list and passes the
output of one command to the input of another. Similarly, boolean logical operators execute
commands based on whether a previous command succeeded (or returned True or 0) or failed
(returned False or non-zero).
Let’s take a look at the AND (&&) boolean operator first, which executes a command only if the
previous command succeeds (or returns True or 0):
1 | kali@kali:~$ user2=kali |
In this example, we first assigned the username we are searching for to the user2 variable. Next,
we use the grep command to check if a certain user is listed in the /etc/passwd file, and if it is,grep returns True and the echo command is executed. However, when we try searching for a user
that we know does not exist in the /etc/passwd file, our echo command is not executed.
When used in a command list, the OR (||) operator is the opposite of AND (&&); it executes the next
command only if the previous command failed (returned False or non-zero):
1 | kali@kali:~$ echo $user2 |
In the above example, we took our previous command a step further and added the OR (||) operator
followed by a second echo command. Now, when grep does not find a matching line and returns
False, the second echo command after the OR (||) operator is executed instead.
These operators can also be used in a test to compare variables or the results of other tests. When
used this way, AND (&&) combines two simple conditions, and if they are both true, the combined
result is success (or True or 0).
Consider this example:
1 | kali@kali:~$ cat ./and.sh |
In this example, we used AND (&&) to test multiple conditions and since both variable comparisons
were true, the whole if line succeeded, so the then branch executed.
When used in a test, the OR (||) boolean operator is used to test one or more conditions, but only
one of them has to be true to count as success.
Let’s take a look at an example:
1 | kali@kali:~$ cat ./or.sh |
In this example, we used OR (||) to test multiple conditions and since one of the variable
comparisons was true, the whole if line succeeded, so the then branch executed.