Bash Scripting
Variables, arrays, control flow, error handling, trap, and production-grade scripting patterns.
Overview
Bash is the dominant shell for system automation. Production scripts must be written with defensive defaults.
Defensive Defaults
Always start scripts with:
- -e — exit on any non-zero return
- -u — treat unset variables as errors
- -o pipefail — fail a pipeline if any command in it fails
Variables and Quoting
Always double-quote variable expansions: "$variable" not $variable — prevents word splitting and glob expansion. Use ${variable:-default} for a default when unset.
Exit Codes and trap
0 is success; anything else is failure. Use trap to register cleanup functions:
Process Substitution
Process substitution feeds command output as a file:
Diffs two sorted outputs without temporary files.
Key concepts
- set -euo pipefail
- Defensive defaults every production script should start with. -e exits on error, -u treats unset variables as an error, -o pipefail fails the whole pipeline on the first non-zero command.
- Double quoting
- Always quote variable expansions: "$var" not $var. Prevents word splitting and glob expansion.
- trap
- Register functions to run on shell exit or signals. trap cleanup EXIT ensures temp files are deleted even when the script exits early.
- Exit codes
- 0 is success; anything else is failure. Scripts should propagate exit codes correctly.
- Process substitution
- diff <(cmd1) <(cmd2) feeds command output as named pipes. Avoids temp files.
When to use it
- Writing deployment scripts, cron jobs, and CI/CD pipeline steps
- Automating repetitive system administration tasks
- Designing error handling that cleans up temp files even on failure
Interview questions
- Write a bash script that downloads a file, processes it, and cleans up temp files even if the script fails mid-way.
- Explain the difference between $*, "$*", $@, and "$@" when passing arguments.
Sign up free to read the full topic
More Linux topics
Start free on Cariara · Coding problems · System design studio