Shell Scripting Basics with Safe, Fail-Fast Bash
I wrote reliable Bash scripts using a strict mode (set -euo pipefail), quoted variables, and conditionals, then linted with shellcheck. Fail-fast settings made scripts abort on the first error instead of silently continuing in a broken state.
Objective & Context
Most shell bugs come from unquoted variables and ignored errors. This lab establishes a safe scripting baseline and static analysis, the foundation the advanced scripting and sysadmin labs build on.
Environment & Prerequisites
- Bash 5.x and shellcheck.
- A task to automate (backup, report).
- A test directory for safe execution.
flowchart LR
W[Write script] --> SC[shellcheck]
SC -->|clean| R[run with strict mode]
SC -->|warnings| W
R --> E{error?}
E -->|yes| Abort[abort + nonzero exit]
Step-by-Step Execution
1. Strict-mode script skeleton
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
target="${1:?usage: backup.sh DIR}"
tar -czf "backup-$(date +%F).tgz" "$target"
2. Lint before running
shellcheck backup.sh3. Run and check exit status
./backup.sh /etc; echo "exit=$?"In backup.sh line 5: (no issues found)
exit=0
Validation & Testing
Call the script with a missing argument and an invalid path and confirm it aborts with a clear non-zero exit. Pass criteria: shellcheck reports clean, undefined variables fail under -u, and errors abort under -e.
Advanced: Troubleshooting
- Word splitting: always quote
"$var"; set IFS deliberately. - Silent failures:
set -epluspipefailsurfaces errors in pipelines. - Unset variable crashes: provide defaults with
${var:-default}.
Key Results
- Adopted fail-fast strict mode as the script default.
- Caught common bugs pre-run with shellcheck.
- Eliminated word-splitting issues through consistent quoting.
- Returned meaningful exit codes for pipeline integration.