Shell scripting best practices
#!/usr/bin/env bash
set -o errexit
set -o pipefail
First line (shebang) tell us which interpreter to use. We recommend using #!/usr/bin/env bash
for portability. Different *nixes put bash
in different places, so using /usr/bin/env
is a workaround to find the first bash
found on the PATH
. (Avoid using sh
)
Next, you must always use a set -o errexit
or set -e
for short. This option makes your script exits whenever a command returned with non-zero status code.
set -o pipefail
help you avoid expression like error here | true
to be succeed. (This is not what you want)
Some other options are:
set -o xtrace
or set -x
for short: print every expression before execute it. It really helpful when debugging/build script.All error messages should go to STDERR
Example: echo "ERROR OCCUR" > &2
To declare new variable, you should use declare var=value
.
Simply use readonly var=value
.
We prefer to user double square brackets [[ ]]
in statement because those provide cleaner syntax, easy to use.
Inside [[ ]]
we allowed to user regular expression.
Use $(command)
instead of backticks.