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
|
|
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