quangkeu95
1/2/2018 - 1:04 PM

Shell scripting best practices

Shell scripting best practices

From the top

#!/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.

STDOUT vs STDERR

All error messages should go to STDERR Example: echo "ERROR OCCUR" > &2

Variables

To declare new variable, you should use declare var=value.

Constants

Simply use readonly var=value.

Conditionals

We prefer to user double square brackets [[ ]] in statement because those provide cleaner syntax, easy to use. Inside [[ ]] we allowed to user regular expression.

Command substitution

Use $(command) instead of backticks.

References