$ cd ../
$ cat /backups/brain/
0028
Make Bash Scripts Failsafe
1
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:
1
2
3
4
$ 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:

1
IFS=$'\n\t'

Due to the following non-expected behavior:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
## 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

$ cd ../