Scripting and Automation
Scripting and Automation tests whether you can write small, safe Bash programs and schedule them. Expect shebangs, variables and quoting, conditionals, loops, exit codes, and cron or systemd timers.
Bash essentials
- Start with #!/usr/bin/env bash; run bash -n script.sh to syntax-check and shellcheck for static analysis.
- Quote expansions: "$var", "$@", "$(command)". Unquoted values undergo word splitting and globbing.
- Positional parameters are $1 and $#; $@ expands to all arguments; $? is the last exit status; exit 1 signals failure.
- Use [ ] for POSIX test or [[ ]] in Bash; quote variables inside [ ].
Scheduling and safety
- cron fields are minute, hour, day-of-month, month, and day-of-week; cron has a minimal PATH, so use absolute paths.
- systemd timers pair a .timer with a .service and support OnCalendar and persistent=true.
- set -euo pipefail stops on errors, unset variables, and pipeline failures, but test its effects.
Worked example
A script must alert when /var is over 90% full: #!/usr/bin/env bash set -euo pipefail usage=$(df --output=pcent /var | tail -1 | tr -dc '0-9') if (( usage > 90 )); then echo "WARNING: /var at ${usage}%" >&2; exit 1; fi Reasoning: df --output=pcent gives a clean percentage, tr strips the % sign, arithmetic comparison avoids string bugs, and stderr plus exit 1 lets monitoring catch it.
Traps
- Unquoted variables and rm -rf "$dir" when dir is empty.
- Relying on cron's environment.
- Using = inside [ ] for numeric comparison instead of -eq.
- CRLF line endings causing bad interpreter errors.