Shell Scripting and Automation Questions
Shell-language craft for operations work: Bash and POSIX sh scripting, pipes and redirection, quoting and word splitting, exit codes and set -euo pipefail (including failures inside pipelines), traps and cleanup, argument parsing with getopts, functions and arrays, parameter expansion, here-documents, and text processing with grep, sed, awk and jq, including streaming pipelines over very large log, CSV and JSON Lines files. Also covers writing robust, idempotent, portable scripts (locking, atomic file updates, retries with backoff, safe temp files, GNU versus BSD differences), background jobs and signals, bounded parallelism and SSH fan-out, cron-driven jobs such as log rotation, backups, atomic deploys and health-check watchdogs, secure scripting (eval injection, secrets, path traversal), and debugging, testing and linting shell with ShellCheck and bats. Boundary: general automation design and Python or Go tooling, Linux host administration tasks, observability and alerting design, security detection engineering, and generic algorithmic coding problems are covered elsewhere.
Write a backup script that takes incremental snapshots of a data directory, keeps daily, weekly and monthly generations, verifies each backup and cleans up on failure. What would make you distrust its first successful run?
Sample Answer
Direct answer
Use rsync with --link-dest to build each daily snapshot as a full-looking directory tree in which unchanged files are hard links to yesterday's copy, so only changed files consume space. Build the snapshot in a staging directory, verify it with a checksum comparison against the source, and publish it with one atomic rename only if verification passes; a trap removes the staging directory on any failure. Promote the daily snapshot to weekly (Sundays) and monthly (the 1st) with hard-link copies, then prune each tier to its retention count (7 daily, 4 weekly, 6 monthly). The first successful run deserves distrust because it is a full copy: the incremental path, the retention path and, above all, the restore path have not been exercised yet.
The script
#!/usr/bin/env bash
# snapshot-backup.sh SRC DEST
# Hard-linked incremental snapshots (rsync --link-dest) with daily, weekly and monthly generations.
# DEST/daily/YYYY-MM-DD kept: 7 (every run)
# DEST/weekly/YYYY-MM-DD kept: 4 (promoted on Sundays)
# DEST/monthly/YYYY-MM-DD kept: 6 (promoted on the 1st)
set -euo pipefail
src=${1:?usage: snapshot-backup.sh SRC DEST}; dest=${2:?usage: snapshot-backup.sh SRC DEST}
today=${TODAY:-$(date +%F)} # TODAY is only overridden by tests
keep_daily=7 keep_weekly=4 keep_monthly=6
min_files=${MIN_FILES:-1} # refuse to snapshot a source that looks empty
stage=$dest/.inprogress
[[ -d $src ]] || { echo "source $src is missing" >&2; exit 2; }
mkdir -p -- "$dest"/{daily,weekly,monthly}
exec 9>"$dest/.lock"; flock -n 9 || { echo "another backup is running" >&2; exit 0; }
cleanup() { local rc=$?; if (( rc != 0 )); then rm -rf -- "$stage"; echo "FAILED (status $rc), partial snapshot removed" >&2; fi; }
trap cleanup EXIT
if [[ -e $dest/daily/$today ]]; then echo "snapshot $today already exists"; exit 0; fi
# 1. Sanity: an unmounted or emptied source must not become a "successful" backup.
files=$(find "$src" -type f | wc -l)
(( files >= min_files )) || { echo "source has $files files, expected at least $min_files" >&2; exit 3; }
# 2. Copy into a staging directory, hard-linking unchanged files to the previous snapshot.
rm -rf -- "$stage"
prev=$(find "$dest/daily" -mindepth 1 -maxdepth 1 -type d | sort | tail -n 1)
link=(); [[ -n $prev ]] && link=(--link-dest="$prev")
rsync -aH --numeric-ids --delete "${link[@]}" -- "$src"/ "$stage"/
# 3. Verify: a checksum comparison against the source must list zero differences.
diff_out=$(rsync -aH --numeric-ids --checksum --dry-run --itemize-changes --delete -- "$src"/ "$stage"/)
if [[ -n $diff_out ]]; then echo "verification found differences:" >&2; echo "$diff_out" >&2; exit 4; fi
# 4. Publish atomically: the name appears only after verification passed.
mv -- "$stage" "$dest/daily/$today"
echo "snapshot $today: $files files, verified"
# 5. Promote with hard links (no extra space), then prune each tier.
(( $(date -d "$today" +%u) == 7 )) && cp -al -- "$dest/daily/$today" "$dest/weekly/$today"
[[ $(date -d "$today" +%d) == 01 ]] && cp -al -- "$dest/daily/$today" "$dest/monthly/$today"
prune() {
local dir=${1:?} n=$2 d
while IFS= read -r d; do
rm -rf -- "${dir:?}/$d"; echo "pruned ${dir##*/}/$d"
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -r | tail -n +"$(( n + 1 ))")
}
prune "$dest/daily" "$keep_daily"; prune "$dest/weekly" "$keep_weekly"; prune "$dest/monthly" "$keep_monthly"
Reading the script
The rsync flags. Each flag below is in the rsync manual.
-a(archive) is shorthand for-rlptgoD: recurse into directories, copy symlinks as symlinks, and preserve permissions, modification times, group, owner and device files. It does not include-H.-Hpreserves hard links that exist inside the source tree.--numeric-idskeeps the owner and group as raw numbers instead of translating them through user and group names, which is what a backup wants when the restore happens on a different machine.--deleteremoves files from the destination that no longer exist in the source, so the copy mirrors the source exactly.--link-dest=DIRis the heart of the design: when a file is unchanged compared with the same path underDIR(the previous snapshot), rsync makes a hard link to it instead of copying the data. A hard link is a second directory entry for the same file data, so it costs almost no space.--checksummakes rsync compare files by a content checksum instead of by size and modification time.--dry-run(-n) reports what it would do without doing it.--itemize-changes(-i) prints one coded line for every difference found, so a dry run with--checksumand--itemize-changesprints nothing when source and copy are identical.- The trailing
/in"$src"/means "the contents of the directory", and--marks the end of the options.
link=(); [[ -n $prev ]] && link=(--link-dest="$prev") and "${link[@]}". link is an array. It stays empty on the very first run (no previous snapshot) and otherwise holds the single word --link-dest=<previous snapshot>. "${link[@]}" expands to each element as its own word, so an empty array vanishes from the command line and a path containing spaces stays one word. Tested in the container: with prev empty, show a "${link[@]}" b received 2 words; with prev=/bk/daily/2026-10-04 it received 3, the middle one --link-dest=/bk/daily/2026-10-04, and a prev of /my backups/2026-10-04 still gave 3 words.
trap cleanup EXIT and local rc=$?. A trap runs a command when an event happens; EXIT fires whenever the script ends, success or failure. $? is the exit status of the last command, so cleanup copies it into rc on its first line, before any other command can change it. A script that does exit 4 made the trap report trap saw status 4, and a script that simply finished made it report 0. Only a non-zero status triggers the removal of .inprogress.
(( $(date -d "$today" +%u) == 7 )) && cp -al .... date -d "$today" +%u prints the weekday number, 1 for Monday to 7 for Sunday (checked: 2026-10-04 gives 7 and 2026-10-05 gives 1). (( ... == 7 )) is an arithmetic test that succeeds only for 7, and && runs the cp only when the test succeeded. In cp -al, -a copies everything with its attributes and -l makes hard links instead of copying data. The monthly line does the same with date +%d, the day of the month, compared with 01.
How it behaves
- Incremental by hard links. A snapshot directory looks complete, but a file that did not change is the same inode (the filesystem's single record of that file's data) as in the previous snapshot. Deleting an old snapshot only frees the files no newer snapshot still links to.
- Atomic publish. Work happens in
.inprogress. The dated name appears only after verification, so a snapshot that exists indaily/is a verified one. The base for--link-destis chosen fromdaily/only, so a failed run can never become the base of the next one. - Verification. The second
rsyncis a dry run with--checksum: it reads both sides in full and lists every difference. Any output fails the backup (exit 4). For a live data directory the comparison can race with writers, so pointSRCat a filesystem snapshot (LVM, btrfs, ZFS) when the data changes while the backup runs. - Cleanup on failure. The
EXITtrap deletes.inprogresswhenever the exit status is non-zero. Earlier snapshots are never modified. - Idempotence and concurrency. A non-blocking
flockprevents overlapping runs, and a snapshot that already exists for today is not redone. - Guard against an empty source. An unmounted or emptied source would otherwise produce a "successful" backup of nothing, and the verification step would pass, because an empty staging copy matches an empty source.
MIN_FILESmakes that a failure (exit 3). - Weekly and monthly generations.
date +%uis 7 on Sunday (ISO numbering, Monday is 1).cp -alcreates the promoted copy with hard links, so a weekly or monthly generation costs directory entries, not data. If a Sunday run is missed there is no weekly for that week; promoting the first successful run of each ISO week removes that gap.
Test run
The simulation runs one backup per day from 2026-08-01 to 2026-10-05 (66 days), with TODAY overriding the date, one 1 MiB file that never changes and a notes file that changes every day (with a new modification time each day). Then it checks retention against an independent calculation, inspects hard links, repeats a day that already has a snapshot, and injects two failures (an empty source and an unreadable file).
run.sh:
cd /w
shellcheck -s bash snapshot-backup.sh && echo "shellcheck clean"
mkdir -p /data/docs /bk; head -c 1048576 /dev/urandom > /data/big.bin; echo v0 > /data/docs/notes.txt
echo "== simulate 2026-08-01 .. 2026-10-05, one run per day, notes.txt changes daily"
for off in $(seq 0 65); do
d=$(date -d "2026-08-01 +$off day" +%F)
echo "$d" > /data/docs/notes.txt; touch -d "$d 12:00" /data/docs/notes.txt
TODAY=$d bash snapshot-backup.sh /data /bk > /dev/null
done
echo "== daily"; ls /bk/daily | tr '\n' ' '; echo
echo "== weekly"; ls /bk/weekly | tr '\n' ' '; echo
echo "== monthly"; ls /bk/monthly | tr '\n' ' '; echo
echo "== expected weekly (last 4 Sundays) and monthly (1st of month)"
python3 - <<'P'
import datetime as dt
days=[dt.date(2026,8,1)+dt.timedelta(n) for n in range(66)]
print("weekly :", " ".join([str(d) for d in days if d.isoweekday()==7][-4:]))
print("monthly:", " ".join([str(d) for d in days if d.day==1][-6:]))
P
echo "== hard links: unchanged file shares one inode across snapshots, changed file does not"
stat -c '%h links inode %i %n' /bk/daily/2026-10-05/big.bin /bk/daily/2026-10-05/docs/notes.txt /bk/daily/2026-10-04/docs/notes.txt
echo "== disk use of all snapshots (KiB) vs one snapshot"
du -sk /bk | cut -f1; du -sk /bk/daily/2026-10-05 | cut -f1
echo "== same day twice"; TODAY=2026-10-05 bash snapshot-backup.sh /data /bk
echo "== empty source is refused"; mkdir /empty; TODAY=2026-10-06 bash snapshot-backup.sh /empty /bk; echo "exit: $?"; ls -A /bk | tr '\n' ' '; echo
echo "== unreadable file, run as an unprivileged user"
mkdir -p /bk2 && chown 1000:1000 /bk2; echo secret > /data/docs/root-only.txt; chmod 000 /data/docs/root-only.txt
chmod 755 /w
setpriv --reuid=1000 --regid=1000 --clear-groups env TODAY=2026-10-06 bash snapshot-backup.sh /data /bk2; echo "exit: $?"
ls -A /bk2 /bk2/daily | tr '\n' ' '; echo
Run in an Ubuntu 24.04 container with rsync 3.2.7:
shellcheck clean
== simulate 2026-08-01 .. 2026-10-05, one run per day, notes.txt changes daily
== daily
2026-09-29 2026-09-30 2026-10-01 2026-10-02 2026-10-03 2026-10-04 2026-10-05
== weekly
2026-09-13 2026-09-20 2026-09-27 2026-10-04
== monthly
2026-08-01 2026-09-01 2026-10-01
== expected weekly (last 4 Sundays) and monthly (1st of month)
weekly : 2026-09-13 2026-09-20 2026-09-27 2026-10-04
monthly: 2026-08-01 2026-09-01 2026-10-01
== hard links: unchanged file shares one inode across snapshots, changed file does not
14 links inode 2418380 /bk/daily/2026-10-05/big.bin
1 links inode 2418863 /bk/daily/2026-10-05/docs/notes.txt
2 links inode 2418857 /bk/daily/2026-10-04/docs/notes.txt
== disk use of all snapshots (KiB) vs one snapshot
1072
1028
== same day twice
snapshot 2026-10-05 already exists
== empty source is refused
source has 0 files, expected at least 1
FAILED (status 3), partial snapshot removed
exit: 3
.lock daily monthly weekly
== unreadable file, run as an unprivileged user
rsync: [sender] send_files failed to open "/data/docs/root-only.txt": Permission denied (13)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1356) [sender=3.2.7]
FAILED (status 23), partial snapshot removed
exit: 23
/bk2: .lock daily monthly weekly /bk2/daily:
Reading the result: the seven newest days remain in daily, the last four Sundays in weekly, and the 1st of each of the three months in monthly (the tier would keep six, but only three exist in a 66-day run); the Python lines compute the same weekly and monthly sets independently. The unchanged 1 MiB file has 14 links, which is 7 daily plus 4 weekly plus 3 monthly directory entries pointing at one inode, while the daily notes file has one link and its Sunday copy two. Everything retained (7 daily, 4 weekly and 3 monthly directories) occupies 1072 KiB in total, against 1028 KiB for one snapshot on its own. The failure cases left no staging directory and no new snapshot: an empty source exited 3, and an unreadable file (running as an unprivileged user) exited 23, which is rsync's "some files were not transferred".
The tally behind those numbers (measured in a repeat of the same 66-day run: 1072 KiB in total, 1028 KiB for one snapshot). The unchanged big.bin has one inode, referenced from 7 daily + 4 weekly + 3 monthly directories, so 14 entries and 14 links, but its 1024 KiB is stored once. notes.txt changes every day, so every daily snapshot has its own inode, 7 in all. A weekly snapshot was made by cp -al from the daily one of that day, so it shares that inode while the daily copy exists: the weekly snapshots of 09-13, 09-20 and 09-27 are no longer in daily/ and hold 3 more inodes, while the one for 10-04 shares an inode with a daily snapshot. In the same way, the monthly snapshots of 08-01 and 09-01 hold 2 more inodes, and the one for 10-01 shares one. That gives 7 + 3 + 2 = 12 distinct notes.txt inodes (find /bk -name notes.txt -printf '%i\n' | sort -u | wc -l printed 12 and find /bk -name notes.txt | wc -l printed 14). Each holds an 11-byte file, which the filesystem stores in one 4 KiB block. So the total is 1024 + 12 x 4 = 1072 KiB, and one snapshot alone is 1024 + 4 = 1028 KiB; the 44 KiB difference is the 11 extra notes.txt blocks. Directories counted as 0 KiB on this filesystem (overlayfs), and other filesystems charge for them, so expect a larger total elsewhere.
A restore check on a fresh, tiny dataset (this is what a restore drill looks like):
mkdir -p /data/docs /bk; head -c 100000 /dev/urandom > /data/big.bin; echo hello > /data/docs/a.txt
bash snapshot-backup.sh /data /bk
mkdir /restore; rsync -a /bk/daily/*/ /restore/
diff -r /data /restore && echo "restore identical"
snapshot 2026-10-06: 2 files, verified
restore identical
What would make me distrust the first successful run
- It was a full copy, so the incremental logic has not run. Check the second run: it should add almost no space and show hard-link counts above 1 on unchanged files (as above). A destination that cannot hard-link would give you a full copy per snapshot, and the link counts are where you would see it. Executed on an 8 MiB FAT-formatted loop image mounted with
mount -o loop:rsync -a --link-destexited 0 and quietly copied the data again (both snapshot files showed 1 link), whilecp -alfailed withcp: cannot create hard link '/fat/weekly1/d/f' to '/fat/daily/1/d/f': Operation not permitted(status 1), so a destination that cannot hard-link both wastes space and breaks the weekly and monthly promotion. - rsync decides "unchanged" from size and modification time. If a file is rewritten with the same size and the same timestamp, rsync links the old content into the new snapshot and nothing looks wrong. The checksum verification is what catches it. This reproduces it:
mkdir -p /data /bk; printf 'AAAAA' > /data/notes.txt; touch -d '2026-10-01 12:00:00' /data/notes.txt
TODAY=2026-10-01 bash snapshot-backup.sh /data /bk
printf 'BBBBB' > /data/notes.txt; touch -d '2026-10-01 12:00:00' /data/notes.txt # same size, same mtime
TODAY=2026-10-02 bash snapshot-backup.sh /data /bk; echo "exit: $?"
ls /bk/daily
snapshot 2026-10-01: 1 files, verified
verification found differences:
>fc........ notes.txt
FAILED (status 4), partial snapshot removed
exit: 4
2026-10-01
In that line >fc........ notes.txt, the first character > says the file would be received into the destination (it would be transferred). f says the item is a regular file. c says its checksum differs, which is possible only because of --checksum. Each . stands for an attribute that is unchanged: size, modification time, permissions, owner, group and so on. rsync's own first pass saw the same size and time and skipped the file; only the checksum run noticed the difference.
- It has never been restored. A backup that has not been restored and compared is a hypothesis. Schedule a restore drill into a scratch directory and compare, including permissions and a database dump if the directory holds a live database (copying database files while it runs gives an inconsistent backup).
- The source may have been wrong. An empty mount, a path typo, exclusions that skip data, or files the backup user cannot read (exit 23) all produce plausible-looking success. Compare file counts and sizes against what you expect.
- Metadata and scope. Run as root to keep ownership; add
-A -Xfor access control lists (ACLs) and extended attributes if the system uses them (the destination and rsync build must support them). - The failure path is untested until you break it. Cause each failure on purpose, as above, and confirm an alert fires: a backup that fails silently is the real danger.
- Same host, same failure domain. Snapshots on the machine they protect do not survive its loss; copy them offsite.
Design the skeleton of a Bash command-line tool with start, stop and status subcommands and a global verbose flag. It should print helpful usage on invalid input and return exit codes that callers can script against.
Sample Answer
Direct answer
Structure the tool as: constants for exit codes at the top, small helpers (usage, die, usage_error), one function per subcommand (cmd_start, cmd_stop, cmd_status), a loop that parses global options (before the subcommand), and a case that dispatches. Invalid input prints a one-line error plus the usage text to stderr and exits 2; --help prints usage to stdout and exits 0. Exit codes are a contract callers script against, so define them once and document them: 0 success, 1 operational failure, 2 usage error, 3 "not running" from status (the convention used by Linux init-script status actions, so monitoring tools that expect it understand it).
The skeleton
#!/usr/bin/env bash
# svc: start, stop and status for one background process.
# exit codes: 0 ok | 1 operational failure | 2 usage error | 3 status: not running
set -u
readonly PROG=${0##*/}
readonly EX_OK=0 EX_FAIL=1 EX_USAGE=2 EX_NOT_RUNNING=3
STATE_DIR=${SVC_STATE_DIR:-/tmp/svc}
PIDFILE=$STATE_DIR/svc.pid
STOP_TIMEOUT=${SVC_STOP_TIMEOUT:-5} # seconds to wait after SIGTERM before SIGKILL
read -r -a SVC_CMD <<< "${SVC_CMD:-sleep 300}" # the managed command, split once into an array
verbose=0
usage() {
cat <<USAGE
Usage: $PROG [-v|--verbose] <command>
Commands:
start launch the service (exit 0 if it is already running)
stop stop the service (exit 0 if it is already stopped)
status exit 0 if running, 3 if not
Exit codes: 0 ok, 1 failure, 2 usage error, 3 not running (status only)
USAGE
}
log() { printf '%s\n' "$*"; }
vlog() { if ((verbose)); then printf '%s: %s\n' "$PROG" "$*" >&2; fi; return 0; }
die() { printf '%s: %s\n' "$PROG" "$1" >&2; exit "$EX_FAIL"; }
usage_error() { printf '%s: %s\n' "$PROG" "$1" >&2; usage >&2; exit "$EX_USAGE"; }
running_pid() { # print the pid and return 0 only if that process is alive
local pid
[[ -r $PIDFILE ]] || return 1
read -r pid < "$PIDFILE" || return 1
[[ $pid =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null || return 1
printf '%s\n' "$pid"
}
cmd_start() {
(($# == 0)) || usage_error "start takes no arguments"
local pid
if pid=$(running_pid); then log "already running"; vlog "pid $pid"; return "$EX_OK"; fi
mkdir -p "$STATE_DIR" || die "cannot create $STATE_DIR"
vlog "launching: ${SVC_CMD[*]}"
nohup "${SVC_CMD[@]}" > "$STATE_DIR/svc.log" 2>&1 &
pid=$!
printf '%s\n' "$pid" > "$PIDFILE"
sleep 0.2
kill -0 "$pid" 2>/dev/null || { rm -f "$PIDFILE"; die "exited immediately, see $STATE_DIR/svc.log"; }
log "started"; vlog "pid $pid"
}
cmd_stop() {
(($# == 0)) || usage_error "stop takes no arguments"
local pid i
if ! pid=$(running_pid); then rm -f "$PIDFILE"; log "not running"; return "$EX_OK"; fi
kill "$pid" 2>/dev/null || die "cannot signal pid $pid"
for ((i = 0; i < STOP_TIMEOUT * 10; i++)); do
kill -0 "$pid" 2>/dev/null || break
sleep 0.1
done
if kill -0 "$pid" 2>/dev/null; then
vlog "SIGTERM ignored for ${STOP_TIMEOUT}s, sending SIGKILL"
kill -KILL "$pid" 2>/dev/null
sleep 0.1
kill -0 "$pid" 2>/dev/null && die "pid $pid will not die"
fi
rm -f "$PIDFILE"
log "stopped"
}
cmd_status() {
(($# == 0)) || usage_error "status takes no arguments"
if running_pid > /dev/null; then log "running"; return "$EX_OK"; fi
log "not running"; return "$EX_NOT_RUNNING"
}
while (($#)); do # global options come before the subcommand
case $1 in
-v|--verbose) verbose=1; shift ;;
-h|--help) usage; exit "$EX_OK" ;;
--) shift; break ;;
-*) usage_error "unknown option: $1" ;;
*) break ;;
esac
done
(($#)) || usage_error "missing command"
command=$1; shift
case $command in
start) cmd_start "$@" ;;
stop) cmd_stop "$@" ;;
status) cmd_status "$@" ;;
*) usage_error "unknown command: $command" ;;
esac
exit $?
Words used in the script
- pid file: a small file holding the process id (the number the operating system gives a running process), so a later
svc stoporsvc statusknows which process to check or signal. nohup: runs the command so it ignores the hangup signal sent when the terminal that started it closes; the trailing&puts it in the background.- SIGTERM and SIGKILL: signals are messages the kernel delivers to a process.
kill PIDsends SIGTERM, a polite "please terminate" that a program may handle or ignore;kill -KILL PIDsends SIGKILL, which cannot be caught or ignored and ends the process immediately. kill -0: sends no signal at all, but reports through its exit status whether the process exists, which makes it a liveness test./proc/PID/comm: the Linux virtual file that holds the short name of the command running as that pid (executed: for the demo service it printssleep), so a script can check that a pid still belongs to the expected program.readonly: marks a variable as constant for the rest of the script, soEX_USAGEcannot be reassigned by accident.${0##*/}:$0is the path the script was started as;##*/removes the longest prefix ending in a slash, leaving the bare file name. Run as./svcor/usr/local/bin/svc,PROGbecomessvceither way.
Design choices worth defending:
- Global flag before the subcommand (
svc -v start): the option loop runs first and stops at the first non-option word, which is the subcommand. Subcommand-specific flags would be parsed inside eachcmd_*function. Each subcommand rejects stray arguments (start extrais a usage error), so typos fail loudly. - Idempotent
startandstop: starting a running service and stopping a stopped one both exit 0, because the desired state already holds. A caller that loops "stop, then start" in a deploy script should not break on the second half of a retry.statusis the command that reports state through its exit code (0 or 3), so scripts can writeif svc status; then .... - Verbose goes to stderr (
vlog) so it never pollutes output a caller captures from stdout. - Liveness is checked with
kill -0, which sends no signal but reports whether the process exists. A pid file that points at a dead process counts as "not running", and stop cleans it up. (Pid reuse after a long outage can make an old pid file point at an unrelated process; for production use, also compare the process name from/proc/PID/comm, or let systemd own the process.) - Stop is TERM, wait, then KILL: polite first, bounded wait (
SVC_STOP_TIMEOUT), force only if ignored. If even SIGKILL fails, exit 1. - The managed command is split into an array once (
read -r -a) and launched as"${SVC_CMD[@]}", with noeval.
Executed run
export SVC_STATE_DIR=/tmp/svc-demo
rm -rf "$SVC_STATE_DIR"
t() {
printf '$ svc'; printf ' %s' "$@"; printf '\n'
out=$(./svc "$@" 2>&1); rc=$?
printf '%s\n' "$out" | head -n 2 | sed 's/^/ /'
echo " (exit $rc)"
}
t status
t -v start
t start
t status
t stop
t status
t stop
t frobnicate
t --colour start
t
t start extra
echo '--- a service that ignores SIGTERM'
export SVC_CMD=./stubborn.sh SVC_STOP_TIMEOUT=1
t start
t -v stop
t status
stubborn.sh stands in for a service that ignores the polite signal: trap "" TERM tells the shell to ignore SIGTERM, and exec sleep 300 replaces the shell with sleep, which keeps that ignore setting.
#!/bin/sh
trap "" TERM
exec sleep 300
$ svc status
not running
(exit 3)
$ svc -v start
svc: launching: sleep 300
started
(exit 0)
$ svc start
already running
(exit 0)
$ svc status
running
(exit 0)
$ svc stop
stopped
(exit 0)
$ svc status
not running
(exit 3)
$ svc stop
not running
(exit 0)
$ svc frobnicate
svc: unknown command: frobnicate
Usage: svc [-v|--verbose] <command>
(exit 2)
$ svc --colour start
svc: unknown option: --colour
Usage: svc [-v|--verbose] <command>
(exit 2)
$ svc
svc: missing command
Usage: svc [-v|--verbose] <command>
(exit 2)
$ svc start extra
svc: start takes no arguments
Usage: svc [-v|--verbose] <command>
(exit 2)
--- a service that ignores SIGTERM
$ svc start
started
(exit 0)
$ svc -v stop
svc: SIGTERM ignored for 1s, sending SIGKILL
stopped
(exit 0)
$ svc status
not running
(exit 3)
The lifecycle behaves as described: status is 3 before start and after stop, a second start reports "already running" and exits 0, a second stop reports "not running" and exits 0. All four invalid-input cases (unknown command, unknown option, missing command, extra argument) exit 2 and print an error line followed by the usage text (the harness trims each case to the first two lines, so only the error line and the first usage line show). The last block shows the SIGKILL path, announced by -v.
The harness trims each case to two lines. Untrimmed, the usage text and the start extra error look like this (executed):
$ svc -h
Usage: svc [-v|--verbose] <command>
Commands:
start launch the service (exit 0 if it is already running)
stop stop the service (exit 0 if it is already stopped)
status exit 0 if running, 3 if not
Exit codes: 0 ok, 1 failure, 2 usage error, 3 not running (status only)
(exit 0)
$ svc start extra
svc: start takes no arguments
Usage: svc [-v|--verbose] <command>
Commands:
start launch the service (exit 0 if it is already running)
stop stop the service (exit 0 if it is already stopped)
status exit 0 if running, 3 if not
Exit codes: 0 ok, 1 failure, 2 usage error, 3 not running (status only)
(exit 2)
Exit-code contract
| Code | Meaning | Who relies on it |
|---|---|---|
| 0 | the requested state holds (start, stop) or the service is running (status) | scripts using if svc status |
| 1 | operational failure: cannot create the state directory, process exited immediately, would not die | alerting, deploy pipelines |
| 2 | usage error: wrong command, option or argument count | humans and CI authors |
| 3 | status only: not running | monitoring |
Pitfalls
- Never print usage and exit 0 on bad input; callers would treat a typo as success.
- Keep exit codes below 126, which shells use for "found but not executable" (126) and "command not found" (127); 128+N means killed by signal N.
- A
startthat returns before the process is actually serving only proves it did not crash in the first 0.2 seconds; a readiness probe (poll a port or health URL) is the next step.
A script with #!/bin/sh works on your laptop but fails inside an Alpine container. What Bash-specific features probably crept in, how do you find them, and how do you decide between rewriting for POSIX sh and just requiring Bash?
Sample Answer
Direct answer
On Alpine, /bin/sh is the ash shell from BusyBox (one small program that bundles minimal versions of the standard utilities), not Bash. It follows POSIX (the standard that defines portable shell behaviour) plus some extras. A script that begins #!/bin/sh but uses Bash-only syntax (arrays, ${var^^}, here-strings <<<, (( )), brace ranges like {1..3}) fails there, or worse, silently behaves differently. Find them by running the script with the target sh in continuous integration (CI) and by running ShellCheck in sh mode. Then decide: rewrite to POSIX when the script is short glue that has to run in minimal images; require Bash (change the shebang to #!/usr/bin/env bash and install it) when the logic really needs arrays or Bash features.
Why it works on the laptop
The laptop's /bin/sh is usually more permissive. On macOS and on Red Hat style systems /bin/sh is Bash itself (I checked an AlmaLinux 9 image: /bin/sh is bash, and the constructs I probed matched Bash), and Bash in sh mode still accepts most Bash syntax. Debian and Ubuntu use dash (the Debian Almquist shell, a small, fast POSIX shell), which is stricter. Alpine uses BusyBox ash (BusyBox's version of the same Almquist shell), whose feature set depends on how that BusyBox was built.
What crept in
This script has the usual suspects:
#!/bin/sh
set -eu
hosts=(web1 web2 db1)
env_name=${1:-prod}
if [[ $env_name == prod* ]]; then
echo "production run"
fi
for h in "${hosts[@]}"; do
echo "checking $h"
done
echo "${env_name^^} done"
count=$(( ${#hosts[@]} * 2 ))
echo "total checks: $count"
echo -e "tab:\tseparated"
set -eu makes the script stop at the first failing command (-e) and treat any use of an unset variable as an error (-u); both are POSIX.
$ sh deploy-check.sh
deploy-check.sh: line 3: syntax error: unexpected "("
exit=2
BusyBox stops at the first syntax error (the array on line 3), so one message can hide other problems. ShellCheck in sh mode reports the Bash-only constructs it recognises (the SC3xxx codes are its "not defined in POSIX sh" family):
$ shellcheck -s sh -f gcc deploy-check.sh
deploy-check.sh:3:7: warning: In POSIX sh, arrays are undefined. [SC3030]
deploy-check.sh:5:4: warning: In POSIX sh, [[ ]] is undefined. [SC3010]
deploy-check.sh:5:17: warning: In POSIX sh, == in place of = is undefined. [SC3014]
deploy-check.sh:8:11: warning: In POSIX sh, array references are undefined. [SC3054]
deploy-check.sh:11:7: warning: In POSIX sh, case modification is undefined. [SC3059]
deploy-check.sh:14:6: warning: In POSIX sh, echo flags are undefined. [SC3037]
$ shellcheck -s sh deploy-check-posix.sh; echo "exit=$?"
exit=0
Each line reads file:line:column: severity: message [code]. The report has six entries, but line 12, count=$(( ${#hosts[@]} * 2 )), also uses array syntax and ShellCheck does not list it here (checked by running it alone: it reports only an unused variable and an unassigned hosts). A linter is a net with holes, so a clean run does not prove the script is POSIX: run the script itself under the target shell as well.
Measure, do not assume: constructs against three shells
probe.sh runs one snippet per construct under a named shell and compares the output with what Bash prints. The constructs, in plain words:
a=(x y)is an array, a variable holding a numbered list;[[ ]]is Bash's extended test (pattern matching);(( ))is an arithmetic command;{1..3}is brace expansion (the shell writes out1 2 3).echo -emakesechointerpret backslash escapes such as\t;${v^^}upper-cases a value;${v//a/X}replaces everyawithX;${v:1:2}takes two characters starting at offset 1.<<<(here-string) feeds a string to a command's standard input;<(cmd)(process substitution) presents a command's output as if it were a file;source fileruns a file's commands in the current shell (POSIX spells it.).function f { ...; }is the Bash keyword form of defining a function;localmakes a variable private to a function;set -o pipefailmakes a pipeline fail if any stage fails, not only the last;$'a\tb'is ANSI-C quoting, which turns\tinto a real tab.
How the helper works: probe label want snippet runs $sh_bin -c "$snippet" (-c means "take the commands from this string"), merges error messages into the output with 2>&1, keeps only the first line with head -n 1, and captures it with $(...). If that equals want (what Bash prints) the verdict is same, otherwise DIFFERENT; printf '%-18s %-9s %s\n' pads the three columns. tab=$(printf '\t') stores a tab character so tab results can be compared.
The last probe line looks odd because the snippet contains single quotes. A single quote cannot appear inside a single-quoted string, so the line splices four pieces together: 'printf "%s\n" $', then "'" (a quote character in double quotes), then 'a\tb', then "'" again. The snippet that reaches the shell is printf "%s\n" $'a\tb'.
# usage: probe.sh SHELL ; prints what each construct does under SHELL and whether it matches bash
sh_bin=$1
tab=$(printf '\t')
probe() {
label=$1; want=$2; snippet=$3
got=$($sh_bin -c "$snippet" 2>&1 | head -n 1)
if [ "$got" = "$want" ]; then verdict=same; else verdict=DIFFERENT; fi
printf '%-18s %-9s %s\n' "$label" "$verdict" "$got"
}
probe 'array' 'y' 'a=(x y); echo ${a[1]}'
probe '[[ ]]' 'match' '[[ abc == a* ]] && echo match'
probe '(( ))' '2' 'i=1; ((i++)); echo $i'
probe 'brace expansion' '1 2 3' 'echo {1..3}'
probe 'echo -e' "a${tab}b" 'echo -e "a\tb"'
probe '${v^^}' 'ABC' 'v=abc; echo ${v^^}'
probe '${v//a/X}' 'bXnXnX' 'v=banana; echo ${v//a/X}'
probe '${v:1:2}' 'el' 'v=hello; echo ${v:1:2}'
probe 'here-string' 'hi' 'cat <<< hi'
probe 'process subst' 'hi' 'cat <(echo hi)'
probe 'source' '1' 'echo x=1 > /tmp/s.sh; source /tmp/s.sh; echo $x'
probe 'function keyword' 'hi' 'function f { echo hi; }; f'
probe 'local' '1' 'f() { local x=1; echo $x; }; f'
probe 'pipefail' '1' 'set -o pipefail; false | true; echo $?'
probe 'dollar-quote' "a${tab}b" 'printf "%s\n" $'"'"'a\tb'"'"
The reference run under Bash matches every expectation. In the two tables after it, DIFFERENT followed by an error message means the construct failed outright. DIFFERENT with no error (brace expansion on both shells, and echo -e and $'...' on dash) means the shell ran the command and printed something else, which is the dangerous case because nothing stops the script. same means the construct works in that shell.
$ sh probe.sh bash # reference
array same y
[[ ]] same match
(( )) same 2
brace expansion same 1 2 3
echo -e same a b
${v^^} same ABC
${v//a/X} same bXnXnX
${v:1:2} same el
here-string same hi
process subst same hi
source same 1
function keyword same hi
local same 1
pipefail same 1
dollar-quote same a b
Alpine 3 (BusyBox v1.37.0 here):
$ busybox | head -n 1 # the version banner; probe.sh itself does not print it
BusyBox v1.37.0 (2026-01-10 15:38:28 UTC) multi-call binary.
$ sh probe.sh sh # Alpine 3, BusyBox ash
array DIFFERENT sh: syntax error: unexpected "("
[[ ]] same match
(( )) DIFFERENT sh: i++: not found
brace expansion DIFFERENT {1..3}
echo -e same a b
${v^^} DIFFERENT sh: syntax error: bad substitution
${v//a/X} same bXnXnX
${v:1:2} same el
here-string DIFFERENT sh: syntax error: unexpected redirection
process subst same hi
source same 1
function keyword same hi
local same 1
pipefail same 1
dollar-quote same a b
Ubuntu 24.04 (dash):
$ sh probe.sh sh # Ubuntu 24.04, dash
array DIFFERENT sh: 1: Syntax error: "(" unexpected
[[ ]] DIFFERENT sh: 1: [[: not found
(( )) DIFFERENT sh: 1: i++: not found
brace expansion DIFFERENT {1..3}
echo -e DIFFERENT -e a b
${v^^} DIFFERENT sh: 1: Bad substitution
${v//a/X} DIFFERENT sh: 1: Bad substitution
${v:1:2} DIFFERENT sh: 1: Bad substitution
here-string DIFFERENT sh: 1: Syntax error: redirection unexpected
process subst DIFFERENT sh: 1: Syntax error: "(" unexpected
source DIFFERENT sh: 1: source: not found
function keyword DIFFERENT sh: 1: Syntax error: "}" unexpected
local same 1
pipefail DIFFERENT sh: 1: set: Illegal option -o pipefail
dollar-quote DIFFERENT $a\tb
Three lessons from the data. First, BusyBox 1.37 accepted [[ ]], ${v//a/X}, ${v:1:2}, source, pipefail, echo -e, process substitution, the function keyword and local, but rejected arrays, (( )), brace expansion, ${v^^} and here-strings, so "Alpine has no Bash features" is too strong and "it works on Alpine" depends on the BusyBox version. Second, brace expansion and (( )) fail silently or with a confusing message: echo {1..3} prints the literal {1..3}, and ((i++)) prints i++: not found (ash reads ((i++)) as a subshell inside a subshell running a command named i++, so the status is 127). Without set -e the script carries on past it; with set -e it stops there. Both were checked on BusyBox ash. Third, dash rejects most of the list and differs on echo -e (prints -e), so testing on both catches more than either alone.
Finding them systematically
- Run the script under the real target shell in the real image (
docker run --rm -v "$PWD":/w alpine:3 sh /w/script.sh), including every code path. - Run
shellcheck -s sh script.sh; its SC3xxx warnings are exactly the "undefined in POSIX sh" constructs. Debian'scheckbashismsis another tool for this (I did not run it here). - Test under
dashas well, because it is the strictest common/bin/sh. - Note that
bash --posixis not a POSIX checker: it still accepts many extensions.
The POSIX rewrite
#!/bin/sh
set -eu
hosts="web1 web2 db1"
env_name=${1:-prod}
case $env_name in
prod*) echo "production run" ;;
esac
count=0
for h in $hosts; do
echo "checking $h"
count=$((count + 2))
done
echo "$(printf '%s' "$env_name" | tr '[:lower:]' '[:upper:]') done"
echo "total checks: $count"
printf 'tab:\tseparated\n'
$ sh deploy-check-posix.sh prod # Alpine
production run
checking web1
checking web2
checking db1
PROD done
total checks: 6
tab: separated
exit=0
Arrays became a space-separated list (safe here because the words contain no spaces), [[ == prod* ]] became case, ${v^^} became tr, (( )) became $(( )), and echo -e became printf.
Rewrite or require Bash?
Recommendation: rewrite to POSIX if the script is under roughly a screen, has to run in minimal images (FROM alpine, distroless images that hold only the application and its libraries with no shell at all, and init containers, the short setup containers that run before the main one in Kubernetes) and needs only simple lists; require Bash when it needs arrays of values with spaces, associative arrays, [[ ]] regex matching or mapfile, because emulating those in POSIX is where bugs come from. Requiring Bash costs apk add bash (an extra package and a slightly bigger image) plus a shebang that says what you mean. Whichever you pick, make the shebang match the dialect, put shellcheck -s sh or -s bash in CI, and run the script in the target image in CI so a regression fails the build, not the deploy.
Write a deploy script that releases a new build into a web root with no downtime and a fast rollback: unpack into a timestamped directory, verify its integrity, switch traffic over atomically, and prune old releases. It should run under plain /bin/sh.
Sample Answer
Direct answer
Keep every build in its own directory under releases/, serve the web root through a current symlink (a symbolic link: a tiny filesystem entry that holds a path and stands in for it, so current can point at whichever release directory is live), and deploy by building a new symlink beside the old one and renaming it over current. A rename is one atomic step (all or nothing: no other process can ever observe it half done), so requests see the old release or the new one and never a half-copied tree, and rollback is the same rename pointed at the previous directory. The script below does this in plain POSIX sh: verify a checksum, unpack into a hidden staging directory, rename it to its final release name, switch, run a health check, roll back automatically if it fails, then prune to a retention count.
The layout
/srv/www/shop/
current -> releases/20260105T101500Z (what the web server's root points at)
releases/
20260105T091000Z/
20260105T101500Z/
.deploy.lock/ (exists only while a deploy runs)
Release names are UTC timestamps (date -u +%Y%m%dT%H%M%SZ), so a plain text sort is chronological order and no extra bookkeeping file is needed. The symlink target is relative (releases/ID), so the whole tree can be moved or mounted elsewhere.
The script
#!/bin/sh
# Usage: deploy.sh deploy ARTIFACT.tar.gz (expects ARTIFACT.tar.gz.sha256 beside it)
# deploy.sh rollback
set -eu
WEBROOT=${WEBROOT:?set WEBROOT, e.g. /srv/www/shop}
RELEASES=$WEBROOT/releases
CURRENT=$WEBROOT/current
KEEP=${KEEP:-5}
HEALTH_CMD=${HEALTH_CMD:-} # runs with the live symlink as its working directory
RELEASE_ID=${RELEASE_ID:-$(date -u +%Y%m%dT%H%M%SZ)}
staging=
log() { printf '%s\n' "$*"; }
die() { printf 'deploy: %s\n' "$*" >&2; exit 1; }
case $KEEP in *[!0-9]*|0|1) die "KEEP must be an integer >= 2 (one live + one rollback target)";; esac
current_id() { basename -- "$(readlink "$CURRENT" 2>/dev/null || true)"; }
switch_to() { # build the new link beside the old one, then rename it over the old one
ln -s "releases/$1" "$WEBROOT/.current.$$"
mv -fT "$WEBROOT/.current.$$" "$CURRENT" # rename(2): readers see old or new, never neither
}
health_ok() {
[ -z "$HEALTH_CMD" ] || (cd "$CURRENT" && sh -c "$HEALTH_CMD")
}
prune() {
cur=$(current_id)
ls -1 "$RELEASES" | sort -r | awk -v keep="$KEEP" 'NR > keep' |
while IFS= read -r old; do
if [ "$old" != "$cur" ]; then rm -rf -- "${RELEASES:?}/$old"; log "pruned $old"; fi
done
}
deploy() {
artifact=${1:?usage: deploy.sh deploy ARTIFACT.tar.gz}
[ -f "$artifact" ] || die "no such artifact: $artifact"
[ ! -e "$RELEASES/$RELEASE_ID" ] || die "release $RELEASE_ID already exists"
( cd "$(dirname -- "$artifact")" && sha256sum -c "$(basename -- "$artifact").sha256" ) \
|| die "checksum mismatch, nothing was unpacked"
if tar -tzf "$artifact" | grep -Eq '(^/|(^|/)\.\.(/|$))'; then
die "archive contains absolute or ../ paths"
fi
staging=$RELEASES/.incoming-$RELEASE_ID
mkdir -p "$staging"
tar -xzf "$artifact" -C "$staging"
mv "$staging" "$RELEASES/$RELEASE_ID" # a release name only ever appears fully unpacked
staging=
prev=$(current_id)
switch_to "$RELEASE_ID"
if ! health_ok; then
if [ -n "$prev" ]; then
switch_to "$prev"
rm -rf -- "${RELEASES:?}/$RELEASE_ID" # a build that failed its check must never become a rollback target
die "health check failed, rolled back to $prev"
fi
die "health check failed on the first release (nothing to roll back to)"
fi
log "live: $RELEASE_ID (was: ${prev:-none})"
prune
}
rollback() {
cur=$(current_id)
[ -n "$cur" ] || die "nothing is live"
target=$(ls -1 "$RELEASES" | sort | awk -v cur="$cur" '$0 < cur { p = $0 } END { print p }')
[ -n "$target" ] || die "no release older than $cur"
switch_to "$target"
log "live: $target (rolled back from $cur)"
}
mkdir -p "$RELEASES"
mkdir "$WEBROOT/.deploy.lock" 2>/dev/null || die "another deploy or rollback is running"
trap 'rmdir "$WEBROOT/.deploy.lock"; if [ -n "$staging" ]; then rm -rf "$staging"; fi' EXIT
trap 'exit 1' HUP INT TERM # a signal becomes a normal exit, so the EXIT trap above still runs
case ${1:-} in
deploy) shift; deploy "$@" ;;
rollback) rollback ;;
*) die "usage: deploy.sh deploy ARTIFACT.tar.gz | rollback" ;;
esac
Reading the less obvious lines
set -eu:-emakes the script exit as soon as a command fails, and-uturns a use of an unset variable into an error instead of silently treating it as empty.${WEBROOT:?set WEBROOT, e.g. /srv/www/shop}: expands to the variable's value, but if the variable is unset or empty the shell prints the message and exits. The same form guards the delete inprune:rm -rf -- "${RELEASES:?}/$old"would otherwise collapse torm -rf -- /r1ifRELEASESwere ever empty. Executed underdash, an emptyRELEASESstops withRELEASES: parameter not set or nulland exit status 2 before anything is removed.case $KEEP in *[!0-9]*|0|1) die ...: eachcasearm lists glob patterns separated by|.*[!0-9]*is any string containing a character that is not a digit, and0and1are the two numbers that leave no rollback target. An unset or emptyKEEPnever reaches thecase, because${KEEP:-5}has already turned it into 5. Executed:abc,0and1are rejected;2,5and an emptyKEEP(which becomes 5) are accepted..current.$$:$$is the process id of the running shell, so the temporary link gets a name such as.current.23that is unique to this run (two runs cannot clash) and starts with a dot so a directory listing does not show it.rename(2): the operating system call that renames a file or link; the(2)is the manual-page section for system calls. When the destination already exists it is replaced in a single step, which is what makes the switch atomic.trap '...' EXITandtrap 'exit 1' HUP INT TERM: the first runs the quoted commands when the script ends normally, hitsdie, or is stopped byset -e. A shell killed by a signal does not necessarily run its EXIT trap (executed: dash left the lock directory behind after SIGTERM), so the second trap turns hangup, interrupt and terminate into an ordinaryexit 1, which then fires the EXIT trap and releases the lock and deletes the staging directory. A trap runs once the foreground command in progress returns, and SIGKILL or a power cut cannot be trapped at all: after one of those, check that no deploy is running and remove.deploy.lockby hand.ls -1 "$RELEASES" | sort -r | awk -v keep="$KEEP" 'NR > keep':ls -1lists one name per line,sort -rputs the newest timestamp first, andawkprints only the lines whose line numberNRis greater thankeep(-vpasses the shell'sKEEPinto awk as the variablekeep). With the three releases on disk whenpruneruns in the last deploy of the run below (r1, r2 and the new r6) andKEEP=2, the stages produce:
ls -1: r1 r2 r6
sort -r: r6 r2 r1
NR > 2: r1 <- this one is deleted; r6 and r2 stay
Why each step is there
- Integrity first.
sha256sum -cchecks the tarball against a.sha256file produced at build time (a hash computed in the build pipeline and shipped alongside, not computed on the server, which would only prove the file equals itself). A mismatch aborts before anything is unpacked. A second check rejects archives whose member paths are absolute or contain.., which would write outside the release directory. - Unpack to a hidden staging directory, then rename it. A release name under
releases/therefore only ever exists fully unpacked. A failed unpack or an interrupting signal leaves a.incoming-*directory that the traps remove; afterkill -9it can survive, and the listing ignores it either way. - Atomic switch.
ln -sfnlooks atomic but is not: it removes the old link and then creates the new one, leaving a moment with nocurrent. Creating a temporary link.current.<pid>and usingmv -fT(-Tmeans "treat the destination as a file", somvreplaces the link instead of moving the new link into the directory it points to) is a singlerename(2).-Tis in GNUmv, and it also worked in the BusyBoxmvof an Alpine container; check your target'smvbefore relying on it. - Health check after the switch, with automatic rollback.
HEALTH_CMDruns with the live symlink as its working directory, so it tests what the web server is actually serving. In production it would be something likecurl -fsS http://127.0.0.1/healthz. On failure the script switches back to the previous release, deletes the failed release directory (otherwiserollback, which picks the next older name, could later put a build that is known to be bad back in front of users) and exits 1, so the pipeline sees the failed deploy. - Retention.
prunekeeps the newestKEEPreleases and never removes the live one.KEEPmust be at least 2 so there is always a rollback target. Release names are generated by the script, so parsinglsoutput is safe here; it would not be for user-supplied names. - One deploy at a time.
mkdirof the lock directory succeeds for exactly one caller, which also works on systems withoutflock.
Executed run
Three builds (v1, v2 good, v3 whose healthz file says broken), a corrupted artifact, a path-traversal archive, a manual rollback and a final deploy with KEEP=2. Run under dash, which is /bin/sh on Debian:
#!/bin/sh
set -eu
export WEBROOT=/tmp/site KEEP=2 HEALTH_CMD='grep -qx ok healthz'
rm -rf "$WEBROOT" /tmp/build; mkdir -p "$WEBROOT" /tmp/build
build() { # build NAME HEALTH_BODY
mkdir "/tmp/build/$1"; echo "page $1" > "/tmp/build/$1/index.html"; echo "$2" > "/tmp/build/$1/healthz"
tar -czf "/tmp/build/$1.tar.gz" -C "/tmp/build/$1" .
( cd /tmp/build && sha256sum "$1.tar.gz" > "$1.tar.gz.sha256" )
}
build v1 ok; build v2 ok; build v3 broken
show() { printf 'current -> %s | releases: %s\n' "$(readlink "$WEBROOT/current")" "$(ls -1 "$WEBROOT/releases" | tr '\n' ' ')"; }
d() { sh ./deploy.sh "$@" || echo "(exit $?)"; }
echo '--- two good deploys'
RELEASE_ID=r1 d deploy /tmp/build/v1.tar.gz | grep -v ': OK'; RELEASE_ID=r2 d deploy /tmp/build/v2.tar.gz | grep -v ': OK'; show
echo '--- broken build fails its health check'
RELEASE_ID=r3 d deploy /tmp/build/v3.tar.gz | grep -v ': OK'; show; cat "$WEBROOT/current/index.html"
echo '--- corrupted artifact'
echo junk >> /tmp/build/v2.tar.gz
RELEASE_ID=r4 d deploy /tmp/build/v2.tar.gz; show
echo '--- path traversal in archive'
mkdir /tmp/build/evil; echo x > /tmp/build/evil/f
tar -czf /tmp/build/evil.tar.gz -C /tmp/build/evil --transform 's,^,../,' f
( cd /tmp/build && sha256sum evil.tar.gz > evil.tar.gz.sha256 )
RELEASE_ID=r5 d deploy /tmp/build/evil.tar.gz | grep -v ': OK'; show
echo '--- manual rollback, then a good deploy prunes to KEEP=2'
d rollback; show; cat "$WEBROOT/current/index.html"
build v6 ok; RELEASE_ID=r6 d deploy /tmp/build/v6.tar.gz | grep -v ': OK'; show
--- two good deploys
live: r1 (was: none)
live: r2 (was: r1)
current -> releases/r2 | releases: r1 r2
--- broken build fails its health check
deploy: health check failed, rolled back to r2
(exit 1)
current -> releases/r2 | releases: r1 r2
page v2
--- corrupted artifact
v2.tar.gz: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
deploy: checksum mismatch, nothing was unpacked
(exit 1)
current -> releases/r2 | releases: r1 r2
--- path traversal in archive
tar: Removing leading `../' from member names
deploy: archive contains absolute or ../ paths
(exit 1)
current -> releases/r2 | releases: r1 r2
--- manual rollback, then a good deploy prunes to KEEP=2
live: r1 (rolled back from r2)
current -> releases/r1 | releases: r1 r2
page v1
live: r6 (was: r1)
pruned r1
current -> releases/r6 | releases: r2 r6
Two details of the driver. grep -v ': OK' hides the v1.tar.gz: OK line that sha256sum -c prints for every artifact that verifies, purely to keep the transcript short. --transform 's,^,../,' is a GNU tar option that applies a sed-style substitution to every member name as the archive is written; here it prepends ../, so the archive holds a member named ../f (listing it with tar -tzf prints ../f), the shape the path check must reject. tar prints its own Removing leading warning while creating it.
Reading the output: the broken release r3 was live only for the duration of its health check, then current went back to r2 and the r3 directory was removed. Both bad artifacts were rejected before any unpacking. rollback moved from r2 to the next older release r1. The last deploy ended with r2 and r6 on disk: r1 was pruned and r6 is live, with r2 kept as the rollback target. Because the failed r3 was deleted, it neither takes a retention slot nor can rollback select it (had it been kept, rollback from r6 would have made the broken r3 live; this was run and confirmed). Keep the build artifact and the health-check output in the pipeline's logs if the post-mortem needs them.
Trade-offs and pitfalls
- Database migrations are not rolled back by a symlink. Rollback only undoes the code. Schema changes must be backward compatible with the previous release (expand, deploy, then contract in a later release).
- "No downtime" also depends on the server. PHP-FPM and nginx can cache the resolved path; nginx setups with PHP commonly need
$realpath_rootin thefastcgi_paramlines and an opcache reset or reload so workers stop using the old directory. Long-running processes that opened files in the old release keep them until restarted. - Shared state (uploads, sessions,
.env) lives outsidereleases/and is symlinked into each release, otherwise every deploy loses it. - If
RELEASE_IDcollides (two deploys in the same second), the script refuses rather than overwriting.
A deployment hook rewrites a configuration file that a running service re-reads, for example a systemd unit file. Design the update so the service never sees a half-written file, an invalid file is never installed, and a failed deploy can be rolled back.
Sample Answer
Direct answer
Stage the new file next to the live one, validate the staged copy, keep the old file as a backup, swap with a single rename(2) (the system call behind mv within one filesystem, which replaces the destination name in one indivisible step), then reload and health-check, and roll back by swapping the backup in the same way. A reader either has the old file open or the new one, never a mix, an invalid file never gets the live name, and the backup is what makes the rollback a one-command operation.
How each requirement is met
| Requirement | Mechanism |
|---|---|
| Service never sees a half-written file | Write to a temp file in the same directory, sync it, then mv over the target. Same directory means same filesystem, so mv is a rename, not a copy followed by a delete. A process that already has the old file open keeps reading the old inode (the file's on-disk record) until it reopens; a process that opens the path gets the complete new file. |
| Invalid file never installed | Validate the staged file, not the live one. For a systemd unit that is systemd-analyze verify. Treat any output as failure, not only a non-zero exit (see the transcript). |
| Failed deploy can be rolled back | Take a timestamped backup before the swap (a hard link costs no copy), then restore it with the same stage-and-rename step if the reload or health check fails. |
| Concurrent deploys do not interleave | An advisory lock (flock) on a lock file; the second deploy exits instead of racing. |
| Ownership and mode preserved | chmod --reference and chown --reference copy them from the old file onto the staged file before the swap. |
The deploy script
Terms used in the script:
set -euo pipefail:-estops the script when a command fails,-utreats an unset variable as an error, and-o pipefailmakes a pipeline fail if any stage fails.exec 9>"$lock"opens the lock file on file descriptor 9 (a small number a process uses to refer to an open file; 0, 1, 2 are taken by standard input, output and error).flock -n 9then asks the kernel for an exclusive lock on it and fails at once if another deploy holds it. The lock is advisory: it only stops programs that also ask for it, nothing prevents some other program from writing the file. All deploys use the same lock, so it works for them.mktemp -p "$dir" ".$base.XXXXXX"creates a new, uniquely named empty file in$dir, replacing the X characters with random ones;--suffix=".service"appends.servicebecausesystemd-analyze verifyexpects that file extension.trap 'rm -f -- "$tmp"' EXITregisters a command to run whenever the script ends, so the temp file is removed on a normal failure.syncasks the operating system to write buffered data to disk now.
#!/usr/bin/env bash
# install-config.sh NEW_FILE TARGET : validate, back up, atomically swap, reload, roll back on failure
set -euo pipefail
new=$1 target=$2
dir=$(dirname -- "$target")
base=$(basename -- "$target")
lock="$dir/.$base.lock"
exec 9>"$lock"
flock -n 9 || { echo "another deploy holds the lock" >&2; exit 75; }
# 1. Stage the candidate in the SAME directory (same filesystem, so mv is a rename(2)).
tmp=$(mktemp -p "$dir" ".$base.XXXXXX" --suffix=".service")
trap 'rm -f -- "$tmp"' EXIT
cp -- "$new" "$tmp"
chmod --reference="$target" -- "$tmp"
chown --reference="$target" -- "$tmp"
# 2. Validate the staged file. An invalid file never reaches the live path.
# verify exits 0 for lines it merely "ignores", so any output at all counts as a failure.
rc=0
out=$(systemd-analyze verify "$tmp" 2>&1) || rc=$?
if (( rc != 0 )) || [[ -n $out ]]; then
echo "REJECTED: validation failed (exit $rc)" >&2
sed 's/^/ /' <<<"$out" >&2
exit 1
fi
# 3. Keep a timestamped backup (hard link: no copy, old inode stays intact after the rename).
backup="$target.bak.$(date +%Y%m%dT%H%M%S)-$$"
ln -- "$target" "$backup"
# 4. Flush the staged data, then swap atomically.
sync -- "$tmp"
mv -f -- "$tmp" "$target"
sync -- "$dir"
echo "installed $target (backup: ${backup##*/})"
# 5. Reload and health-check. On failure, restore the backup with the same atomic swap.
if ! bash -c "${RELOAD_CMD:-true}" || ! bash -c "${HEALTH_CMD:-true}"; then
echo "post-deploy check failed: rolling back" >&2
rb=$(mktemp -p "$dir" ".$base.XXXXXX")
cp --preserve=all -- "$backup" "$rb"
mv -f -- "$rb" "$target"
bash -c "${RELOAD_CMD:-true}" || true
echo "rolled back to ${backup##*/}" >&2
exit 2
fi
Order matters: validate before the backup and swap, sync before the rename (so a power loss cannot leave the new name pointing at unwritten data), and roll back with a copy of the backup renamed into place rather than renaming the backup itself, so the backup survives for the next attempt. RELOAD_CMD and HEALTH_CMD are where the real systemctl daemon-reload && systemctl restart app and a probe such as curl -fsS localhost:8080/healthz go. systemd reads unit files when it is told to (daemon-reload), so writing the file is only half of a unit change.
Worked run
The driver below creates a unit owned by user ID 1000 with mode 640, then deploys a good file, two broken files, and a good file whose health check fails. It ran in an Ubuntu 24.04 container with systemd 255 installed; temp-file names and timestamps differ on every run.
cd /srv/demo
printf '[Service]\nExecStart=/bin/true\n' > app.service
chown 1000:1000 app.service; chmod 640 app.service
printf '[Service]\nExecStart=/bin/true --port 9090\n' > good.service
printf '[Service]\nExecStart=/bin/true --port 9191\n' > newer.service
printf '[Service]\nExecStart=/bin/true\nRestart=sometimes\nBogus\n' > typo.service
printf '[Service]\nExecStart=/opt/app/bin/missing\n' > missing.service
echo "== good file"
./install-config.sh good.service app.service; echo "exit=$?"
ls -ln app.service | awk '{print $1, $3, $4, $9}'
for f in typo.service missing.service; do
echo "== $f"
./install-config.sh "$f" app.service; echo "exit=$?"
done
echo "port line still live: $(grep -c 9090 app.service)"
echo "== health check fails after the swap"
HEALTH_CMD=false ./install-config.sh newer.service app.service; echo "exit=$?"
tail -n 1 app.service
ls -ln app.service | awk '{print $1, $3, $4, $9}'
== good file
installed app.service (backup: app.service.bak.20261006T071618-14)
exit=0
-rw-r----- 1000 1000 app.service
== typo.service
REJECTED: validation failed (exit 0)
/srv/demo/.app.service.8eGfU7.service:3: Failed to parse service restart specifier, ignoring: sometimes
/srv/demo/.app.service.8eGfU7.service:4: Missing '=', ignoring line.
exit=1
== missing.service
REJECTED: validation failed (exit 1)
.app.service.sMNpK3.service: Command /opt/app/bin/missing is not executable: No such file or directory
exit=1
port line still live: 1
== health check fails after the swap
installed app.service (backup: app.service.bak.20261006T071618-59)
post-deploy check failed: rolling back
rolled back to app.service.bak.20261006T071618-59
exit=2
ExecStart=/bin/true --port 9090
-rw-r----- 1000 1000 app.service
Reading the transcript: the two ignoring lines mean systemd found Restart=sometimes (not a valid value, so that setting is dropped) and a line Bogus with no = (not a setting at all, so it is skipped); the file still loads, just without those lines. The owner and mode survived the swap. typo.service was rejected even though systemd-analyze verify exited 0, because it only warned that it was "ignoring" two lines; a gate that checked the exit code alone would have installed a file with a silently dropped Restart= setting. missing.service was rejected on the exit code. After the failed health check the live file is back to the previous good content (--port 9090, not the failed 9191) and the owner and mode are unchanged.
Complexity and edge cases
- Cost is one read and one write of the file (linear in its size) plus constant extra memory; the backup is a hard link, so it adds no data copy.
- The temp file must be on the same filesystem as the target. Staging in
/tmpand moving to/etcmakesmva copy, which is not atomic. - A single file bind-mounted into a container cannot be replaced by rename. Tested:
mvonto a bind-mounted file fails withDevice or resource busy. For those, mount the directory instead. - Rename gives the target a new inode. Hard links to the old file and services holding the old file open keep the old content; a symlink target should be resolved first (
readlink -f) so you replace the real file, not the link. - The lock file and temp files are dot-files in the target directory; the
EXITtrap removes the temp file on normal failure, butkill -9leaves it behind, so a periodic sweep of stale.name.XXXXXXfiles is reasonable. - Backups accumulate; prune to the last N.
Trade-offs
rename protects against torn reads, but it does not make a bad configuration good: validation and a post-reload health check do that. For systemd specifically, prefer a drop-in file (/etc/systemd/system/app.service.d/override.conf) over rewriting the vendor unit, so the diff you validate and roll back is small. If the service cannot tolerate a restart, use reload where the service supports it and keep the rollback path using the same command.
Unlock Full Question Bank
Get access to all 40 Shell Scripting and Automation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.