Shell scripting best practices

last modified: | 2 min read #shell

Over the years, I’ve started to appreciate the power of a well-written shell script. But writing shell scripts can be tricky. Thes best-practices can make your life a lot easier.

General Advice

  • Use bash or POSIX shell, this guarantees compatibility.
  • Use #!/usr/bin/env bash or #!/usr/bin/env sh as shebang.
  • Always quote variable accesses with double quotes.
  • Use stderr for printing error messages.
  • Use long options where possible (like --help instead of -h).

When using Bash

bash hits the sweetspot between portability and developer experience. Writing POSIX-complient shell scripts is generally harder and more error-prone. If you can get away with supporting a single shell, prefer the use of Bash.

  • Use set -euo pipefail at the start of the script.
    • When a command fails, the script exits instead of running the rest of the script.
    • The script will fail when accessing unset variables. When you do want to access a variable use "${VAR-}" instead of "${VAR}".
    • Ensures that a pipeline command fails when one command in the pipeline fails.
  • Create a check on $TRACE environment variable to set set -x.
    • Add [[ ${TRACE:-0} == "1" ]] && set -x
    • This is for debugging scripts… Run it with TRACE=1 bash


#!/usr/bin/env bash
set -euo pipefail
[[ ${TRACE:-0} == "1" ]] && set -x

main() {
    echo "Create awesome scripts!"

main "$@"