Write defensive Bash scripts
8 steps · about 3 h 55 min · Intermediate
- 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.
- 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.
- 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.
- 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.
- 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.
- Redirect output and errors deliberately (guide, Greg's Wiki (Wooledge), 30 min)
Separating stdout and stderr makes scripts composable and their logs useful.
- 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.
- 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.