Writting a shell script to “solve a quick problem” still the default for me. Since it doesn’t happen everyday I tend to forget some of the good defaults.

To help with that, I’ve captured those below:

tl;dr Link to heading

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/usr/bin/env bash

set -o errexit
set -o errtrace
set -o nounset
set -o pipefail

__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

function important_function() {
  echo "do things"
}

important_function

That combined with shellcheck is enough for me for most of the time.

Here is a more holistic / complete boilerplate if you are doing something more serious.

Explanation Link to heading

  • set -o errexit – ensures the script exits when a command fails;
  • set -o errtrace – ensures the script exits when a command fails inside subshells or functions;
  • set -o nounset – ensures the script exits when undeclared variables are used;
  • set -o pipefail – ensures the script exits with a non-zero exit code when a piped command fails.
  • __dir – returns the directory where the shell scipts resides. It is useful when you need to use other resources relative to the script itself.

If you prefer a less explict version of the flags, you can replace lines 3-6 with:

set -eEuo pipefail