Bash boilerplate
The following boilerplate is adopted from Best Practices for Writing Bash Scripts by Kevin van Zonneveld.
set -e
exits the execution upon a command failure. E.g. for a script like
set -e
ls abc
pwd
The error is like
ls: cannot access 'abc': No such file or directory
Note, the line pwd
is never executed.
set -u
exits the execution when a unbound variable is encoutered. E.g. for a script like
set -u
echo $ABC
the error is like
line 3: ABC: unbound variable
set -x
shows the trace of execution. E.g. for a script like
set -x
echo 1
echo 2
the output is
+ echo 1
1
+ echo 2
2
set -o pipefail
returns the non-zero status code of failed command in a pipeline. E.g. for
# set -o pipefail
ls non-existing-file | wc
echo $?
the output is 0
, the return code of wc
; but if we uncomment the first
line. the output is 2, i.e. the return code of ls non-existing-file
.