logical operators in bash

2020-02-11

 | 

~2 min read

 | 

212 words

When I’m working in bash, it’s common that I’ll want to sequence operations together so that one naturally follows another.

For example: $ cd web && ./setup.sh

Most commonly, I only want to run the latter if the former does not exit with an error (as in the example above). That need not always be the case, however. Fortunately, Bash makes it easy to handle several other common situations.

Maxim Egorushkin provided a nice summary on StackOverflow for other options:

To summarize (non-exhaustively) bash’s command operators/separators:

  • | pipes (pipelines) the standard output (stdout) of one command into the standard input of another one. Note that stderr still goes into its default destination, whatever that happen (sic) to be.
  • |& pipes both stdout and stderr of one command into the standard input of another one. Very useful, available in bash version 4 and above.
  • && executes the right-hand command of && only if the previous one succeeded.
  • || executes the right-hand command of || only it the previous one failed.
  • ; executes the right-hand command of ; always regardless whether the previous command succeeded or failed. Unless set -e was previously invoked, which causes bash to fail on an error.

Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!