27.1. Writing Reliable Shell Automation
Shell scripts remain the native automation language of a Debian system: they need no runtime beyond the shell every machine already has, they wrap the same commands an administrator types, and systemd, cron, and installation hooks all invoke them. What separates useful automation from a hazard is a small set of disciplines - explicit inputs, quoted expansions, honest exit statuses, cleanup on every path, and idempotent behavior. This section develops them around one small job: a script that counts the lines of every file in a directory and publishes a report. Create the workspace and the directories the examples use:
$ mkdir -p ~/debian-handbook/automation/{bin,input,reports,config,logs,state,preseed,cloud-init,provisioning}
The command produces no output; mkdir -p creates each missing directory
and succeeds silently if one already exists. Unless a block says otherwise,
the commands in this section run from ~/debian-handbook/automation on
auto1, as john. Install ShellCheck now - it is used in Section 27.1.4:
$ sudo apt install shellcheck
Reading package lists...
Building dependency tree...
Reading state information...
shellcheck is already the newest version (0.10.0-1).
Summary:
Upgrading: 0, Installing: 0, Removing: 0, Not Upgrading: 66
The complete report script is bin/report.sh. Type or paste it into that
file; the listing is the artifact itself, not a transcript:
#!/usr/bin/env bash
set -euo pipefail
readonly program=${0##*/}
dry_run=0
source_dir=
output_dir=
usage() {
printf 'Usage: %s [--dry-run] --source DIR --output DIR\n' "$program" >&2
}
die() {
local message=$1 status=${2:-1}
printf '%s: %s\n' "$program" "$message" >&2
exit "$status"
}
while (($#)); do
case $1 in
--dry-run)
dry_run=1
;;
--source)
source_dir=${2-}
shift
;;
--output)
output_dir=${2-}
shift
;;
-h|--help)
usage
exit 0
;;
*)
usage
exit 64
;;
esac
shift
done
[[ -n $source_dir && -n $output_dir ]] || { usage; exit 64; }
[[ -d $source_dir ]] || die "source directory not found: $source_dir" 2
mkdir -p "$output_dir"
lock_file="$HOME/debian-handbook/automation/.report.lock"
exec 9>"$lock_file"
flock -n 9 || die "another report is already running" 75
report=$(mktemp "$output_dir/.report.XXXXXX")
trap 'rm -f "$report"' EXIT
{
printf 'source: %s\n' "$source_dir"
for path in "$source_dir"/*; do
[[ -f $path ]] || continue
printf '%6d %s\n' "$(wc -l < "$path")" "${path##*/}"
done | LC_ALL=C sort -k2
} > "$report"
if [[ -f $output_dir/report.txt ]] && cmp -s "$report" "$output_dir/report.txt"; then
printf 'No changes: %s\n' "$output_dir/report.txt"
elif ((dry_run)); then
printf 'Dry run: would write %s\n' "$output_dir/report.txt"
diff -u "$output_dir/report.txt" "$report" || true
else
mv "$report" "$output_dir/report.txt"
printf 'Report written: %s\n' "$output_dir/report.txt"
fi
Make it executable; chmod is silent:
$ chmod 755 bin/report.sh
The sections that follow walk through this script part by part, testing each property as it is introduced.
27.1.1. Inputs, Quoting, Exit Status, and Error Handling
The first line of defense is set -euo pipefail. -e aborts the script
when a command fails, -u treats unset variables as errors instead of
silently expanding to nothing, and -o pipefail makes a pipeline fail if
any stage in it fails - without it, production | gzip > backup.gz
reports success when production fails but gzip succeeds. The
exceptions matter: set -e does not fire for commands whose status is
being tested (if, while, the left side of && and ||, or !), so
cmp -s ... && ... remains a test rather than a land mine, and a command
whose failure is expected is handled explicitly, the way the script's
diff -u ... || true marks "diffs found" as a normal outcome
(Section 27.1.3). Chapter 3 introduced these
options; automation is where they stop being style and become safety.
Inputs arrive as arguments, parsed by the while (($#)) loop: it runs
while the argument count is nonzero, matches $1 in a case, consumes
the matched option with the final shift, and for --source/--output
also consumes the value with an inner shift. An unknown option prints
the usage line and exits 64; a missing value or missing directory is
rejected before any work starts. Every place an input value reaches a
command is quoted, deliberately, in one of three forms:
"$source_dir"/*- the parameter is quoted, the glob is not. Quotes prevent the shell from word-splitting the value; the unquoted/*must stay outside them so it still expands to the list of files.wc -l < "$path"- each loop value is one filename, passed whole. An unquoted$pathwould split names at spaces and handwcseveral arguments per file.printf '%6d %s\n' ... "${path##*/}"- the expansion insideprintf's argument list is quoted for the same reason;${path##*/}strips the directory prefix so the report shows a bare file name.
The die helper prints to standard error with the script's own name as a
prefix and exits with the status you pass it, so diagnostics never mix
into the report stream and the caller can tell failure classes apart.
The script uses three deliberately:
| Exit status | Meaning in report.sh |
Origin |
|---|---|---|
| 0 | Report published (or already current) | conventional |
| 2 | Input rejected: source directory missing | die ... 2 |
| 64 | Usage error: unknown or incomplete options | sysexits.h EX_USAGE |
| 75 | Another run holds the lock; try later | sysexits.h EX_TEMPFAIL, the mail-queue "retry" code |
Create the input files and run the job for the first time. The two
printf commands write files - the redirection sends the text to the
file, not the terminal, and there is no output to show:
$ printf 'alpha\nbeta\ngamma\n' > input/alpha.txt
$ printf 'one\ntwo\n' > input/beta.txt
$ bash bin/report.sh --source input --output reports
Report written: reports/report.txt
The report lists each file's line count in a fixed-width column, sorted by name. Read it back:
$ cat reports/report.txt
source: input
3 alpha.txt
2 beta.txt
Now break the inputs the way real callers do. A source directory that does not exist:
$ bash bin/report.sh --source missing --output reports
report.sh: source directory not found: missing
The diagnostic goes to standard error, the script's name prefixes it, and
the exit status is 2 - distinguishable from a usage error in whatever
called it ($? holds the status; test it with if bash bin/report.sh
...; then rather than parsing the text). An option the script never
heard of:
$ bash bin/report.sh --bogus
Usage: report.sh [--dry-run] --source DIR --output DIR
That is exit status 64, printed before the script touched any file. Checking arguments before doing work is what makes a script safe to call from other automation: a caller that gets 64 knows the failure was its own request, not a half-finished job.
27.1.2. Temporary Files, Traps, Locks, and Cleanup
Automation fails in the middle more often than interactive work - the
machine reboots, the network drops, a concurrent run interferes. The
script's last four properties are designed for exactly that. First, the
lock: two runs of the same report at once would both stage a temporary
file and both publish, with the slower one winning whether or not it is
the more current one. flock makes the script refuse instead:
exec 9>"$lock_file"
flock -n 9 || die "another report is already running" 75
exec 9>"$lock_file" opens the lock file for writing and attaches it to
file descriptor 9 for the rest of the script; flock -n 9 tries to take
an exclusive advisory lock on that descriptor without waiting. The lock
belongs to the open file description, so it is released automatically when
the script exits - any exit path, including one caused by set -e.
flock form |
Description |
|---|---|
flock FD |
Lock an already-open file descriptor (the form used above). |
flock -n |
Do not wait: fail immediately if the lock is held. |
flock -x |
Exclusive lock (the default when locking a command). |
flock -w SECONDS |
Wait at most that long before failing. |
flock FILE -c COMMAND |
Run COMMAND holding the lock; used from other programs. |
Watch the lock refuse a second run. Hold the lock from a second terminal
with the command form - the sleep 30 simulates a slow run:
$ flock ~/debian-handbook/automation/.report.lock -c 'sleep 30'
It prints nothing and returns nothing for thirty seconds. In the first terminal, while it runs:
$ bash bin/report.sh --source input --output reports
report.sh: another report is already running
The status is 75: not an error in this run, but "busy, try again" - the
value a scheduler or wrapper can treat differently from real failure.
Let the flock command finish (or stop it with Ctrl+C) before
continuing; the lock is released either way.
Second, the temporary file. mktemp "$output_dir/.report.XXXXXX"
creates a uniquely named file in the output directory - the trailing
XXXXXX is replaced by random characters, and mktemp creates the file
with mode 0600, refusing to clobber anything that already exists. A fixed
name like /tmp/report.tmp would collide between users and runs, and a
predictable name in a world-writable directory invites symlink attacks;
the mktemp pattern avoids both.
mktemp usage |
Description |
|---|---|
mktemp TEMPLATE |
Create a file from a template ending in at least six X. |
mktemp -d TEMPLATE |
Create a unique directory instead. |
mktemp -p DIR TEMPLATE |
Interpret the template relative to DIR. |
Third, the trap. trap 'rm -f "$report"' EXIT installs a handler that
runs when the script exits - normally, through set -e, or on most
signals. Whatever route the script takes out of the middle of its work,
the staged file is removed. Verify that a completed run leaves nothing
behind:
$ find reports -maxdepth 1 -name '.report.*' -print
The empty result is the point: the trap removed .report.XXXXXX after
the mv published it, and a run that failed at any earlier line would
have removed its own staged file the same way.
Fourth, the atomic publish. mv "$report" "$output_dir/report.txt"
renames the staged file over the published one. A rename inside one
filesystem is atomic: readers see either the whole old report or the
whole new one, never a half-written file, and a crash between the write
and the rename costs only the staged copy. This write-then-rename
pattern is the same one Section 27.2.3 applies to /etc files and
Section 27.6 applies to a job's state file; it is the standard way for
automation to update a file that something else might be reading.
27.1.3. Idempotence, Logging, and Dry-Run Design
A job is idempotent when running it twice produces the same result as running it once. For automation that schedulers may retry, that operators may rerun by hand after a failure, and that runs on a schedule whether or not it succeeded last time, idempotence is not a nicety - it is the difference between "run it again, it will settle" and manual cleanup. The script's comparison does it in one place:
if [[ -f $output_dir/report.txt ]] && cmp -s "$report" "$output_dir/report.txt"; then
printf 'No changes: %s\n' "$output_dir/report.txt"
With unchanged inputs, a second run computes the same content, cmp -s
finds no difference, and the script publishes nothing:
$ bash bin/report.sh --source input --output reports
No changes: reports/report.txt
Record the digest of the published report before changing anything -
sha256sum is the same tool Chapter 2 used to
verify installation images:
$ sha256sum reports/report.txt
fb0a364b5763f272105c200ddfe0b3e57ce869df9c96475d4969786c22be244d reports/report.txt
Now change an input, as a nightly job would find its data changed:
$ printf 'delta\n' >> input/alpha.txt
The append is silent. A dry run previews what would be published without touching the report:
$ bash bin/report.sh --source input --output reports --dry-run
Dry run: would write reports/report.txt
--- reports/report.txt 2026-11-23 20:03:05.250173676 +0000
+++ reports/.report.VKsBNM 2026-11-23 20:03:15.234142799 +0000
@@ -1,3 +1,3 @@
source: input
- 3 alpha.txt
+ 4 alpha.txt
2 beta.txt
The diff names the staged file mktemp created, shows the one line that
changed (alpha.txt grew from 3 lines to 4), and nothing was published.
Note the || true on the diff line in the script: diff exits 1 when
files differ, and under set -e that exit would abort the script right
after the message - an explicit, narrow exception. Confirm the published
report is untouched by computing its digest again:
$ sha256sum reports/report.txt
fb0a364b5763f272105c200ddfe0b3e57ce869df9c96475d4969786c22be244d reports/report.txt
The identical digest is the proof: a dry run is safe to run against
production state at any time. Publish for real by running without
--dry-run - and to exercise the quoting rules from Section 27.1.1 at
the same time, make the new input a file whose name contains spaces:
$ printf 'one line\n' > 'input/name with spaces.txt'
$ bash bin/report.sh --source input --output reports
Report written: reports/report.txt
Both pending changes - the appended line and the new file - published in one atomic rename. Check that the awkward name survived the loop whole:
$ grep 'name with spaces' reports/report.txt
1 name with spaces.txt
The line is a single entry because the loop quoted "$path";
Section 27.1.4 shows what the unquoted version does to this same file.
Idempotent scripts also settle after the publish: run once more and the
job reports no changes again.
Logging closes the design. The script writes one line per outcome to
standard output and all diagnostics to standard error, with no timestamps
of its own - the timestamp is the caller's job, and when the caller is
systemd (Section 27.6), the journal adds timestamps, unit identity, and
retention for free. When a script must keep its own log file, append with
>> so runs do not overwrite each other's history, and rotate the file
as Chapter 8 describes; a scheduled job that
redirects its output into an unbounded log is a slow disk leak.
27.1.4. Checking Scripts with ShellCheck
Quoting, expansion, and exit-status mistakes are systematic: the same
handful of errors appear in almost every shell script ever written.
ShellCheck finds them statically - it parses the script and warns about
the failure modes without running anything. On Debian 13 it is packaged
as shellcheck 0.10.0:
shellcheck option |
Description |
|---|---|
| (no options) | Check each named script; exit 1 if any finding is reported. |
-s SHELL |
Override the detected shell (for scripts without a shebang). |
-S SEVERITY |
Only report findings at this level or worse (style, info, warning, error). |
-e CODE[,CODE] |
Exclude specific check codes. |
A clean script produces no output at all:
$ shellcheck bin/report.sh
Silence is the result: no findings, exit status 0. The check is not a
formality - the two scripts built later in this chapter
(bin/install-sudoers.sh in Section 27.2.3 and bin/run-job.sh in
Section 27.6) are held to the same standard. To see what ShellCheck
catches, use the deliberately broken version, bin/broken-quoting.sh,
which counts lines the lazy way:
#!/usr/bin/env bash
set -euo pipefail
input_dir=$1
for file in $input_dir/*; do
wc -l $file
done
$ shellcheck bin/broken-quoting.sh
In bin/broken-quoting.sh line 5:
for file in $input_dir/*; do
^--------^ SC2231 (info): Quote expansions in this for loop glob to prevent wordsplitting, e.g. "$dir"/*.txt .
In bin/broken-quoting.sh line 6:
wc -l $file
^---^ SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean:
wc -l "$file"
For more information:
https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
https://www.shellcheck.net/wiki/SC2231 -- Quote expansions in this for loop...
Both findings point at the same class of bug demonstrated with the
spaced-name file in Section 27.1.3: an unquoted expansion is split on
whitespace and globbed, so input/name with spaces.txt would arrive at
wc as two arguments - the line count of a nonexistent input/name
and an error for with spaces.txt. The suggested fix is exactly the
form bin/report.sh uses: for file in "$input_dir"/* with wc -l
"$file". Run ShellCheck as part of the workflow rather than as an
afterthought - a script that fails it is a script whose next input,
not its current test data, breaks it.