Bash: Using logic expressions as a shorthand for if-then-else control

Bash has a rich set of control structures but it is still common to see logic expressions used a shorthand for if-then-else/tertiary statements.

This can provide a curt and single-line ingestable way of controlling the flow of your Bash script.  For example:

$ [ 1 -eq 1 ] && echo "correct, 1 does indeed equal 1" || echo "impossible!"

correct, 1 does indeed equal 1

$ [ 1 -eq 0 ] && echo "impossible!" || echo "correct, 1 does not equal 0"

correct, 1 does not equal 0

Shows that a simple test expression (e.g. whether 1=1 or 1=0) can be used to emulate an if-then-else or tertiary operator.  This test statement could be any test: file existence, variable value, comparator, etc.

This property of logical expressions is certainly not limited to Bash, and is used by programmers in all languages:

  • logical AND stops processing once first false is found
  • logical OR stop processing once first true is found

Another practical example is using OR to provide a quick assertion.

# file must exist
[ -f ~/.ssh/.authorized_keys ] || { echo "ERROR did not find personal ssh authorized keys file"; exit 3; }

# variable must be populated
[ -n "$myvar" ] || { echo "ERROR the variable 'myvar' was empty"; exit 3; }

If the test passes, then the OR short-circuits and has no need to process the error message and exit.

However, you must understand this syntax can have side effects.  For example, if the test is true but the first expression returns a non-zero result then the second expression will also be evaluated – which is probably unexpected.

$ [ 1 -eq 1 ] && { echo "correct, 1 does indeed equal 1";false; } || echo "impossible!"

correct, 1 does indeed equal 1 
impossible!

 

 

REFERENCES

javascript.info, logical AND returns first falsy value, logical OR returns truthy value