Write defensive Bash scripts

8 steps · about 3 h 55 min · Intermediate

  1. Quote everything that can contain spaces (guide, Greg's Wiki (Wooledge), 20 min)

    Most broken scripts are quoting bugs; fix this habit before learning anything else.

  2. Use parameter expansion for defaults and trimming (guide, Greg's Wiki (Wooledge), 40 min)

    Defaults, error-on-unset and substring removal replace many calls to sed and basename.

  3. Test conditions with [[ ]] and case (guide, Greg's Wiki (Wooledge), 30 min)

    Bash's own test syntax avoids word-splitting traps and handles pattern matching.

  4. Keep lists of files in arrays (guide, Greg's Wiki (Wooledge), 25 min)

    Arrays are the only safe way to hold filenames that may contain spaces.

  5. Structure scripts with functions and main (guide, Google, 25 min)

    A widely used style guide shows how functions, local variables, naming and a main function keep longer scripts maintainable.

  6. Redirect output and errors deliberately (guide, Greg's Wiki (Wooledge), 30 min)

    Separating stdout and stderr makes scripts composable and their logs useful.

  7. Know where set -e fails you (guide, Greg's Wiki (Wooledge), 20 min)

    errexit looks like a safety net but skips many failures; learn its gaps so you check errors explicitly where it matters.

  8. Audit your script against known pitfalls (guide, Greg's Wiki (Wooledge), 45 min)

    Finish by checking your own script against a long list of real-world mistakes.