← All notes

Make Bash Scripts Failsafe

set -euxo pipefail
  • set -e: fail if any command has non-zero exit status
  • set -x: all executed commands are printed to the terminal
  • set -u: reference to undefined variables causes an exit
  • set -o pipefail: prevents errors in a pipeline from being masked:
$ grep some-string /non/existent/file | sort
grep: /non/existent/file: No such file or directory
% echo $?
0

Also it’s recommended to change the default IFS separator to strict mode:

IFS=$'\n\t'

Due to the following non-expected behavior:

#!/bin/bash
names=(
"Aaron Maxwell"
"Wayne Gretzky"
"David Beckham"
)

echo "With default IFS value..."
for name in ${names[@]}; do
echo "$name"
done

echo ""
echo "With strict-mode IFS value..."
IFS=$'\n\t'
for name in ${names[@]}; do
echo "$name"
done
## Output
With default IFS value...
Aaron
Maxwell
Wayne
Gretzky
David
Beckham

With strict-mode IFS value...
Aaron Maxwell
Wayne Gretzky
David Beckham

Source: https://gist.github.com/mohanpedala/1e2ff5661761d3abd0385e8223e16425