Explaining Logical Operators (&& and ||) in Bash
The aim of this pageđź“ť is to present the value of logical operators AND &&
and OR ||
in bash conditionals.
2 min readFeb 20, 2024
$ false && echo howdy!
<NOTHING>
$ true && echo howdy!
howdy!
$ true || echo howdy!
<NOTHING>
$ false || echo howdy!
howdy!
Conditional paths converge
scripts unfold art
1. def: left and right
- the right side of
&&
will only be evaluated if the exit status of the left side is 0 (i.e. true). - the right side of
||
will evaluate only if the left side exit status is non-0 (i.e. false).
2. use: for oneliners
- use the
&&
and||
to reduce an if statement to a single line with the help of a conditional expression - and potentially, for validation methods/subfunctions that are often present right after the beginning of the function
- say we are looking for a file called
/root/Sample.txt
then the traditional iteration would be as follows in shell
if [[ -f /root/Sample.txt ]]; then
echo "file found"
else
echo "file not found"
fi
- These 6 lines can be reduced to an oneliner
[[ -f /root/Sample.txt ]] && echo "file found" || echo "file not found"
- The given one-liner can be seen as a shorthand for an if-else statement, with the format
<predicate> && <consequent> || <alternative>
. - While you can simulate an
if-elif-else
structure using conditional operators, it's generally recommended to use a properif-elif-else
for clarity and maintainability.
Still, Example of using more elaborate conditional operators:
[[ -f /root/Sample.txt ]] && echo "file found" ||
{ [[ -d /root/Sample.txt ]] && echo "a directory found" ||
echo "neither file nor directory found"; }