Skip to content

Instantly share code, notes, and snippets.

@quangkeu95
Last active January 3, 2018 04:10
Show Gist options
  • Save quangkeu95/31b4b7a7a73cb7543962773b5d0de9ee to your computer and use it in GitHub Desktop.
Save quangkeu95/31b4b7a7a73cb7543962773b5d0de9ee to your computer and use it in GitHub Desktop.
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment