Lab: an idempotent backup job with logging and a schedule
Build a backup job that can run twice safely, verifies and publishes its archive atomically, logs a timestamped outcome and any failure to the journal, prunes old archives, and runs from a systemd timer or cron.
Contentsand lesson path
On this page
- Idempotency: a job you can safely run again
- Running unattended: cron and systemd timers
- Lab: build, break and schedule the backup job
- Check your understanding
- Apply it
- Review prompt
Lessons of Scripting Basics
- Anatomy of a script: shebang, arguments and exit codes Concept · 15 min
- Control flow you will actually use: tests, case, loops, functions, read and command substitution Worked example · 25 min
- Quoting, strict mode, tracing with set -x and failing loudly Worked example · 20 min
- Lab: an idempotent backup job with logging and a schedule Lab · 30 min
- Beyond Bash: jq, yq and porting a script to Python Worked example · 25 min
- Check: review and repair a fragile script Knowledge check · 8 questions
What you will learn
- Make a script robust with strict mode, correct quoting, error traps and idempotent steps, and keep it free of ShellCheck warnings.
- Automate a recurring task (backup, cleanup or health check) that runs unattended on a schedule and logs its outcome.
Prerequisites: Linux CLI
01. Idempotency: a job you can safely run again
An operation is idempotent when running it twice leaves the system in the same state as running it once. Scheduled jobs need this property, because they fail halfway for ordinary reasons (a full disk, a reboot, a killed container) and the fix is usually to run them again. If the second run fails because of what the first one left behind, someone has to clean up by hand at 3 a.m.
Three shell habits make a job safe to repeat:
- Create, do not assume.
mkdir /srv/backupsfails if the directory already exists;mkdir -p /srv/backupssucceeds either way. - Replace, do not append.
echo "retention=7" >> app.confadds a duplicate line on every run. Check first (grep -qxF "retention=7" app.conf || echo "retention=7" >> app.conf) or render the whole file from a template. - Publish atomically. Writing straight into the final path (
tar -czf /srv/backups/latest.tar.gz ...) leaves a truncated file if the job dies. Build the file in a staging directory, check it, thenmvit into place. On one filesystem,mvis a singlerename()call, so other programs see either the old file or the complete new one. Across filesystemsmvfalls back to copy-then-delete, which is not atomic, and plainmktemp -doften creates its directory on another filesystem (/tmpmay betmpfs). So create the staging directory inside the destination, as the lab'sbackup.shdoes:mktemp -d "$dest/.staging.XXXXXX". That covers a job that fails or is killed, not a power cut: the rename may reach the disk before the archive's data does, leaving a short or empty file under the final name. If that matters, addsync -- "$staging/$archive"just before themvline ofbackup.shandsync -- "$dest"just after it: the first writes the archive's data to disk, the second writes the rename.
02. Running unattended: cron and systemd timers
A script that works in your terminal can still fail at 02:00, because a scheduler starts it in a much smaller environment. Cron does not read your shell profile, so PATH is usually just /usr/bin:/bin and tools in /usr/local/bin or ~/.local/bin are not found. Nobody sees the output either: cron mails it if mail is set up, and otherwise it is lost. Set PATH in the crontab (or use absolute paths), redirect output to a file, and make the script record its own result.
The usual record is the system journal. logger -t backup-job "result=ok" writes a line tagged backup-job, and the journal adds the time, host and process ID. journalctl -t backup-job later shows every run, even if nobody was watching.
On most current distributions you can use a systemd timer instead. A .timer unit says when, and starts a .service unit that says what. Compared with cron you get:
OnCalendar=*-*-* 02:00:00for the schedule, andRandomizedDelaySec=to spread start times so many hosts do not hit the backup server at the same second;Persistent=true, which starts a run soon after boot if the machine was off when one was due;- the job's output in the journal automatically, with
systemctl list-timersshowing the last and next run.
Whichever you use, set umask 027 (or 077) at the top of the script, so archives that may contain secrets are not created readable by every user.
03. Lab: build, break and schedule the backup job
You will build a backup job that verifies its archive before publishing it, logs a start line and a timestamped outcome to the journal, records failures with their exit code, deletes old archives, and runs from a timer. Then you will break it on purpose and check that the failure is logged.
You need: Linux with Bash, GNU tar, logger and systemd (Ubuntu 22.04 or later, Debian 12 or similar); ShellCheck for step 2. Run everything as your normal user, not as root (root can read the file that step 4 locks). The lab tested Bash 5.1, systemd 249 and ShellCheck 0.11.0.
- Create a lab folder with a small, fixed source tree.
mkdir -p ~/backup-lab/src/data && cd ~/backup-lab
printf 'port=8080\nmode=prod\n' > src/app.conf
printf 'id,total\n1,9.50\n2,12.00\n' > src/data/orders.csv
find src -type f | sortsrc/app.conf
src/data/orders.csv- Save the job as
~/backup-lab/backup.sh. Read it before you run it:
logwrites each message twice: to standard error for a person at a terminal, and withlogger -t backup-jobto the journal, which keeps it with a timestamp.- The
ERRtrap logs the line and status of the command that failed;-Einset -Eeuo pipefailmakes it fire inside functions too. TheEXITtrap runs however the script ends: it removes the staging directory and logs one outcome line,result=okorresult=failed exit=N. tar -tzfreads the new archive back beforemvpublishes it. A bad archive, or a run that fails or is killed before themv, never touches the published archives (a power cut is the exception, see the first section).- Old archives are pruned only after the new one is in place, so a job that keeps failing cannot delete your last good backups.
-mtime +7matches files whose age in whole days is more than 7. STAMPexists only so the lab can use fixed archive names; on a schedule the script uses the current date and time.
#!/usr/bin/env bash
# backup.sh SRC_DIR DEST_DIR: archive SRC_DIR, verify it, publish it, prune old ones
set -Eeuo pipefail # -E: the ERR trap also fires inside functions
umask 027 # archives: owner rw, group r, others nothing
src=${1:?usage: backup.sh SRC_DIR DEST_DIR}
dest=${2:?usage: backup.sh SRC_DIR DEST_DIR}
keep_days=${KEEP_DAYS:-7}
stamp=${STAMP:-$(date +%Y%m%d_%H%M%S)} # set STAMP only to test with a fixed name
archive="backup_${stamp}.tar.gz"
staging=""
log() {
echo "backup-job: $*" >&2 # for a person watching a terminal
logger -t backup-job -- "$*" # for the journal, which outlives the run
}
on_exit() {
local code=$?
if [[ -n "$staging" ]]; then rm -rf -- "$staging"; fi
if (( code == 0 )); then
log "result=ok archive=$archive"
else
log "result=failed exit=$code"
fi
exit "$code"
}
trap 'log "error: line $LINENO failed with status $?"' ERR
trap on_exit EXIT
log "start src=$src dest=$dest"
if [[ ! -d "$src" ]]; then
log "source $src is not a directory"
exit 2
fi
mkdir -p -- "$dest"
staging=$(mktemp -d "$dest/.staging.XXXXXX") # same filesystem as $dest
tar -czf "$staging/$archive" -C "$src" .
tar -tzf "$staging/$archive" > /dev/null # read it back before publishing
mv -f -- "$staging/$archive" "$dest/"
# Prune only after a good archive exists, so a failing job never empties $dest
pruned=$(find "$dest" -maxdepth 1 -name 'backup_*.tar.gz' \
-mtime +"$keep_days" -print -delete | wc -l)
log "pruned=$pruned keep_days=$keep_days"chmod +x backup.sh && shellcheck backup.sh && echo 'shellcheck: no findings'shellcheck: no findings- Run the job twice with the same name, then look inside. The second run succeeds and still leaves exactly one archive, with no
.staging.*folder: the job is idempotent. The journal holds both runs.
STAMP=20261116_020000 ./backup.sh src dest
STAMP=20261116_020000 ./backup.sh src dest
ls -A dest
tar -tzf dest/backup_20261116_020000.tar.gz | sort
stat -c '%A %n' dest/*.tar.gz
journalctl -t backup-job -o cat -n 6backup-job: start src=src dest=dest
backup-job: pruned=0 keep_days=7
backup-job: result=ok archive=backup_20261116_020000.tar.gz
backup-job: start src=src dest=dest
backup-job: pruned=0 keep_days=7
backup-job: result=ok archive=backup_20261116_020000.tar.gz
backup_20261116_020000.tar.gz
./
./app.conf
./data/
./data/orders.csv
-rw-r----- dest/backup_20261116_020000.tar.gz
start src=src dest=dest
pruned=0 keep_days=7
result=ok archive=backup_20261116_020000.tar.gz
start src=src dest=dest
pruned=0 keep_days=7
result=ok archive=backup_20261116_020000.tar.gz- Make the job fail: lock one source file so
tarcannot read it. TheERRtrap names the failing line, theEXITtrap logs the exit code, and the published archive from step 3 is untouched.-o cathides the journal's timestamps here so the output matches; drop it to see when each line was written.
chmod 000 src/data/orders.csv
STAMP=20261116_030000 ./backup.sh src dest; echo "exit=$?"
chmod 644 src/data/orders.csv
ls -A dest
journalctl -t backup-job -o cat -n 3backup-job: start src=src dest=dest
tar: ./data/orders.csv: Cannot open: Permission denied
tar: Exiting with failure status due to previous errors
backup-job: error: line 39 failed with status 2
backup-job: result=failed exit=2
exit=2
backup_20261116_020000.tar.gz
start src=src dest=dest
error: line 39 failed with status 2
result=failed exit=2- Test retention. Copy the archive under an older name, backdate it by 15 days with
touch -d, and run the job again: the old copy is pruned and the recent one stays.
cp dest/backup_20261116_020000.tar.gz dest/backup_20261101_020000.tar.gz
touch -d '15 days ago' dest/backup_20261101_020000.tar.gz
STAMP=20261116_040000 ./backup.sh src dest
ls destbackup-job: start src=src dest=dest
backup-job: pruned=1 keep_days=7
backup-job: result=ok archive=backup_20261116_040000.tar.gz
backup_20261116_020000.tar.gz
backup_20261116_040000.tar.gz- Write the schedule as two systemd user units, which run as you and need no root.
%his your home directory. Save both files in~/backup-lab/units/, then let systemd check them before you install anything:systemd-analyze verifyreports unknown keys and missing programs, andsystemd-analyze calendarshows when the expression fires next.
[Unit]
Description=Back up ~/backup-lab/src into ~/backup-lab/dest
[Service]
Type=oneshot
WorkingDirectory=%h/backup-lab
ExecStart=%h/backup-lab/backup.sh src dest[Unit]
Description=Run backup.service every night at 02:00
[Timer]
OnCalendar=*-*-* 02:00:00
RandomizedDelaySec=10min
Persistent=true
[Install]
WantedBy=timers.targetcd ~/backup-lab/units
systemd-analyze --user verify backup.service backup.timer \
&& echo 'units: no problems found'
systemd-analyze calendar --iterations=2 '*-*-* 02:00:00'
cd ~/backup-labunits: no problems found
Normalized form: *-*-* 02:00:00
Next elapse: Tue 2026-11-17 02:00:00 +07
(in UTC): Mon 2026-11-16 19:00:00 UTC
From now: 30min left
Iter. #2: Wed 2026-11-18 02:00:00 +07
(in UTC): Tue 2026-11-17 19:00:00 UTC
From now: 24h leftTo install them, copy the files to ~/.config/systemd/user/, then run systemctl --user daemon-reload and systemctl --user enable --now backup.timer. A user timer runs only while you are logged in, unless you allow it to run without a session with loginctl enable-linger. For a server, put the same two units in /etc/systemd/system/ with User= in the service and absolute paths instead of %h.
- Prove that an unattended start works, without waiting for 02:00.
systemd-runcreates a temporary timer that starts the job once in 20 seconds, in the same bare environment a real timer uses. Check the timer, wait, then read the journal.
systemd-run --user --unit=backup-test --on-active=20s \
"$HOME/backup-lab/backup.sh" "$HOME/backup-lab/src" "$HOME/backup-lab/dest"
systemctl --user list-timers backup-test.timer
sleep 25; journalctl -t backup-job -n 3 --no-hostnameRunning timer as unit: backup-test.timer
Will run service as unit: backup-test.service
NEXT LEFT LAST PASSED UNIT ACTIVATES
Tue 2026-11-17 01:30:37 +07 19s left n/a n/a backup-test.timer backup-test.service
1 timers listed.
Pass --all to see loaded but inactive timers, too.
Nov 17 01:30:39 backup-job[54402]: start src=/home/learner/backup-lab/src dest=…
Nov 17 01:30:39 backup-job[54415]: pruned=0 keep_days=7
Nov 17 01:30:39 backup-job[54417]: result=ok archive=backup_20261117_013039.tar.gzThe timestamped result=ok line is your evidence that a timer-triggered run worked. After the real timer has fired, systemctl --user list-timers backup.timer fills the LAST and PASSED columns, and journalctl -t backup-job --since today shows the night's run. A log only helps if someone reads it, so let a failure raise an alert: because the script exits non-zero, systemd marks backup.service as failed, and an OnFailure= line in its [Unit] section can start a unit that notifies you; or let your log system alert on result=failed.
If you prefer cron, the same job is one crontab line (edit it with crontab -e) with an explicit PATH and the output redirected to a file. Test it first under a bare environment like cron's: env -i HOME="$HOME" PATH=/usr/local/bin:/usr/bin:/bin /bin/sh -c 'cd "$HOME/backup-lab" && ./backup.sh src dest >> backup.log 2>&1', then read backup.log.
PATH=/usr/local/bin:/usr/bin:/bin
0 2 * * * cd "$HOME/backup-lab" && ./backup.sh src dest >> backup.log 2>&104. Check your understanding
05. Apply it
Turn this skill's practice task, the URL and disk health check, into the same kind of job:
- Log a start line and one
result=line per run withlogger -t, and anERRorEXITtrap that records the exit code. - Run it twice by hand, then once from
systemd-run --on-active, and read the result withjournalctl -t. - Schedule it every five minutes with
OnCalendar=*:0/5(check the expression withsystemd-analyze calendar) or*/5 * * * *in cron.
06. Review prompt
Without looking back: what makes a job idempotent, and why does the staging directory live inside the destination? Which two traps does backup.sh use, and what does each log? Why is the archive checked with tar -tzf before mv, and why is pruning the last step? How do you prove that a timer-triggered run worked, and why might a script that runs by hand fail from cron?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.