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.

Pavol Kutaj

--

$ false && echo howdy! 
<NOTHING>
$ true && echo howdy!
howdy!
$ true || echo howdy!
<NOTHING>
$ false || echo howdy!
howdy!
hAIku: In Picasso’s hand,
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 proper if-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"; }

3. links

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com