Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 3

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

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/backups fails if the directory already exists; mkdir -p /srv/backups succeeds either way.
  • Replace, do not append. echo "retention=7" >> app.conf adds 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, then mv it into place. On one filesystem, mv is a single rename() call, so other programs see either the old file or the complete new one. Across filesystems mv falls back to copy-then-delete, which is not atomic, and plain mktemp -d often creates its directory on another filesystem (/tmp may be tmpfs). So create the staging directory inside the destination, as the lab's backup.sh does: 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, add sync -- "$staging/$archive" just before the mv line of backup.sh and sync -- "$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:00 for the schedule, and RandomizedDelaySec= 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-timers showing 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.

  1. Create a lab folder with a small, fixed source tree.
Terminal
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 | sort
Expected output
src/app.conf
src/data/orders.csv
  1. Save the job as ~/backup-lab/backup.sh. Read it before you run it:
  • log writes each message twice: to standard error for a person at a terminal, and with logger -t backup-job to the journal, which keeps it with a timestamp.
  • The ERR trap logs the line and status of the command that failed; -E in set -Eeuo pipefail makes it fire inside functions too. The EXIT trap runs however the script ends: it removes the staging directory and logs one outcome line, result=ok or result=failed exit=N.
  • tar -tzf reads the new archive back before mv publishes it. A bad archive, or a run that fails or is killed before the mv, 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 +7 matches files whose age in whole days is more than 7.
  • STAMP exists only so the lab can use fixed archive names; on a schedule the script uses the current date and time.
Bash · ~/backup-lab/backup.sh
#!/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"
Terminal
chmod +x backup.sh && shellcheck backup.sh && echo 'shellcheck: no findings'
Expected output
shellcheck: no findings
  1. 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.
Terminal
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 6
Expected output
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-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
  1. Make the job fail: lock one source file so tar cannot read it. The ERR trap names the failing line, the EXIT trap logs the exit code, and the published archive from step 3 is untouched. -o cat hides the journal's timestamps here so the output matches; drop it to see when each line was written.
Terminal
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 3
Expected output
backup-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
  1. 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.
Terminal
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 dest
Expected output
backup-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
  1. Write the schedule as two systemd user units, which run as you and need no root. %h is your home directory. Save both files in ~/backup-lab/units/, then let systemd check them before you install anything: systemd-analyze verify reports unknown keys and missing programs, and systemd-analyze calendar shows when the expression fires next.
INI · ~/backup-lab/units/backup.service
[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
INI · ~/backup-lab/units/backup.timer
[Unit]
Description=Run backup.service every night at 02:00

[Timer]
OnCalendar=*-*-* 02:00:00
RandomizedDelaySec=10min
Persistent=true

[Install]
WantedBy=timers.target
Terminal
cd ~/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-lab
Illustrative output (the dates are from the test run)
units: 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 left

To 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.

  1. Prove that an unattended start works, without waiting for 02:00. systemd-run creates 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.
Terminal
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-hostname
Illustrative output (times, PIDs and paths differ; one long line shortened)
Running 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.gz

The 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.

crontab -e
PATH=/usr/local/bin:/usr/bin:/bin
0 2 * * * cd "$HOME/backup-lab" && ./backup.sh src dest >> backup.log 2>&1

04. Check your understanding

Practice check · 3 questions

Atomic publishing, user timers and pruning check

Three questions on atomic replacement, timers and retention.

Q1. Why does the backup job build its archive in a staging directory inside the destination, then `mv` it into place?
Q2. You install `backup.timer` as a user timer on a server and log out. The next morning `journalctl -t backup-job` shows no run from the night. The unit files pass `systemd-analyze verify`. What is the most likely cause?
Q3. A colleague moves the `find ... -mtime +7 -delete` line of `backup.sh` up to just after the start log line, before `tar`. Then the disk fills and `tar` fails every night for two weeks. What happens to the backups?
Practice only: not graded, not saved, not evidence.

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 with logger -t, and an ERR or EXIT trap that records the exit code.
  • Run it twice by hand, then once from systemd-run --on-active, and read the result with journalctl -t.
  • Schedule it every five minutes with OnCalendar=*:0/5 (check the expression with systemd-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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check