GUIDE 08 / AUTOMATION
Bash scripting
Build scripts with arguments, tests, loops, useful errors, and clear exit codes.
In this guide
Commands use class paths and example filenames. Replace placeholders and inspect the target before making changes.
Start with a small script
The shebang selects Bash when you execute the file directly. Mark a script executable once; Git records its executable bit. Run syntax checks before execution.
#!/bin/bash
# Purpose: Show a short report.
set -euo pipefail
printf "Server: %s\n" "$HOSTNAME"
dateset -e has context-dependent behavior; handle expected failures explicitly with if. -u rejects unset variables, and pipefail exposes failures in pipelines. These settings do not replace validation.
Handle parameters safely
${1:-} gives an empty fallback when argument 1 is absent. $# counts arguments. "$*" joins arguments into one string; "$@" preserves them as separate arguments.
if [[ "${1:-}" == "-h" ]]; then
printf "Usage: %s [note]\n" "$0"
exit 0
fi
printf "%s\n" "$*"Use "$@" when forwarding arguments to another command. Use "$*" when you intentionally want one joined note. Quote variable expansions to preserve spaces.
Use tests and loops
An if tests command success. Shell success is exit status 0; nonzero signals a failure or another condition defined by the program. Each loop needs do and done.
for service in nginx sshd chronyd; do
if systemctl is-active --quiet "$service"; then
printf "OK: %s\n" "$service"
else
printf "FAIL: %s\n" "$service"
fi
doneFor arithmetic thresholds, validate input as numeric before comparing. Under set -e, prefer count=$((count + 1)) when counting failures; a standalone ((count++)) can return status 1 on its first increment.
Read input and diagnose failures
read -r preserves backslashes in typed input. bash -n checks syntax without running the script. bash -x executes the script and prints expanded commands to standard error.
read -r -p "Note: " note
printf "%s\n" "$note"
bash -n ./store.sh
bash -x ./health-check.sh -q 2> trace.txtA trace can reveal credentials or other sensitive values; inspect it before sharing. curl needs -f when a health check should fail on HTTP 4xx/5xx responses. -k disables TLS verification and is not a certificate-health test.