Automation, from a shell script to a workflow · Lesson 1 of 8 · about 30 minutes

Cleanup that can't delete the wrong thing

Old backups fill up a server's disk, so most servers have a nightly job that deletes them. If that job is wrong, it deletes the wrong files, and you can't get them back. This lesson shows four ways the usual one-line cleanup goes wrong, using fake backups, and then builds a script that avoids all four.

By the end you'll know

  • Why a cleanup job is worth automating, and why it's the one to be most careful with
  • Four ways the obvious find ... -delete goes wrong, and how each one happens
  • How to make a dry run the default, so deleting is something you ask for
  • Which guard rails stop a script deleting a system folder, someone else's files, or your last backup
  • How to test a month of backups in a second, with fake files

Before you start

  • You need: Docker, as in the Linux track's first lessons, and the practice folder. On your own computer: git clone https://github.com/Kwamib/automation-practice.git.
  • This track starts where the Linux and Python tracks stop. It uses find from Linux Lesson 3 and Lesson 12, and set -euo pipefail from Linux Lesson 13. If those are new, start there.
  • Where commands run: in a container, with the practice folder inside it at /practice. Every deletion in this lesson happens in /lab, a folder inside the container that disappears when you leave it.
  • The output below is from a real run on November 18, 2026, at about 9am in New York (14:00 UTC). Your dates will be different: the fake backups are dated from the day you make them.

The problem: the disk fills up

A server makes a backup of its database every night. That's the right thing to do. Nobody removes the old ones, so every night the backup folder grows, and one day the disk is full. Then everything on that server stops at once: the database can't write, the app can't log, and the backup that's meant to save you can't be written either.

So every team writes the same small job: every night, delete backups older than 14 days. It's one line with find, it's easy to schedule, and it's the most dangerous kind of job you can automate, for one reason: a mistake in it deletes something, and deleting can't be undone. A report that's wrong is wrong until the next run. A deleted backup is gone.

This lesson breaks the obvious version four ways, on fake backups, then builds one that can't make those mistakes.

The practice folder

On your own computer:

BASH
cd ~/Apps/automation-practice
chmod +x make-fake-backups prune-backups
docker run -it --rm -v "$PWD":/practice -w /practice ubuntu:24.04 bash

Check where you are before you go on, because this lesson deletes things. The prompt should look like root@bbb466de4d84:/practice#: a random name, and /practice. Then:

BASH
hostname; pwd; ls
OUTPUT
bbb466de4d84
/practice
... make-fake-backups  prune-backups ...

If your prompt still looks like your own computer's, you're not in the container. The commands below would then run on your computer. Every lesson that deletes things should start with a check like this, and so should every script.

Fake backups with real ages

make-fake-backups builds a folder of nightly backups: 30 nights of them, a few hundred KB of random bytes each. The trick is touch -d, which sets a file's modification time to any date you like, so each file looks exactly as old as its name says. A month of backups, made in a second.

(Inside the container)

BASH
./make-fake-backups /lab
ls -lA --time-style=+%F /lab/backups
du -sh /lab/backups
OUTPUT
made /lab:
  backups           33 files
  backups/monthly    1 files
  important          1 files
  stopped           10 files
total 6624
-rw-r--r-- 1 root root     78 2026-10-09  README.txt
lrwxrwxrwx 1 root root     12 2026-11-18  archive -> ../important
-rw-r--r-- 1 root root 187392 2026-10-19  backup-2026-10-19.tar.gz
-rw-r--r-- 1 root root 242688 2026-10-20  backup-2026-10-20.tar.gz
...
-rw-r--r-- 1 root root 203776 2026-10-24 'backup-2026-10-24 copy.tar.gz'
-rw-r--r-- 1 root root 195584 2026-10-24  backup-2026-10-24.tar.gz
...
-rw-r--r-- 1 root root 185344 2026-11-16  backup-2026-11-16.tar.gz
-rw-r--r-- 1 root root 230400 2026-11-17  backup-2026-11-17.tar.gz
-rw-r--r-- 1 root root  50000 2026-11-18  backup-2026-11-18.tar.gz.part
lrwxrwxrwx 1 root root     24 2026-11-18  backup-latest.tar.gz -> backup-2026-11-17.tar.gz
drwxr-xr-x 2 root root   4096 2026-11-18  monthly
6.7M	/lab/backups

A real backup folder is never just backups, so this one isn't either. Alongside the 30 nightly files:

  • backup-2026-10-24 copy.tar.gz: a copy someone made by hand, with a space in its name.
  • backup-2026-11-18.tar.gz.part: tonight's backup, still being written.
  • README.txt: a note saying who to ask before deleting anything.
  • backup-latest.tar.gz: a link to the newest backup, so other scripts can always find it.
  • monthly/: a folder of monthly backups, kept for a year on purpose.
  • archive: a link to a folder somewhere else, /lab/important, holding the one backup from before a server move.
  • And /lab/stopped: a second server's backups, which stopped 20 days ago.

The find options in this lesson

find builds its search from options, read left to right. These are the ones this lesson uses:

OptionMeansExample
-name "PATTERN"The file name matches the pattern. * means "anything", and the whole name has to match.-name "*.tar.gz" matches backup-2026-11-17.tar.gz, not backup-2026-11-18.tar.gz.part
-mtime +NLast changed more than N whole days ago. The + means "more than".-mtime +14: 15 days old or older
-mtime NLast changed exactly N whole days ago-mtime 14: 14 days old
-mtime -NLast changed fewer than N whole days ago. The - means "less than".-mtime -14: 0 to 13 days old
-type fOnly regular files: not folders (d), not links (l)Skips monthly/ and backup-latest.tar.gz
-maxdepth 1Don't look in folders below this oneSkips monthly/backup-2026-09-19.tar.gz
-mindepth 1Don't include the starting folder itselfNever lists /lab/backups as a result
-printPrint the path of each match. It's what find does when you don't say otherwise.The safe way to see what -delete would hit
-deleteDelete each match, at the point it appears in the lineAlways last, and only after -print showed the right list
-printf 'FORMAT'Print chosen details of each match: %T@ time changed, %s size, %p path, \0 a NUL byteUsed by prune-backups to sort by age

"Whole days" means rounded down: a file 14 days and 23 hours old is 14 days old to find, so -mtime +14 doesn't match it yet.

Four ways the obvious version goes wrong

1. It deletes more than you meant

The obvious job, written the way most people first write it. First, look at what it matches:

BASH
find /lab/backups -name "*.tar.gz" -mtime +14
find /lab/backups -name "*.tar.gz" -mtime +14 -delete
ls -A /lab/backups/monthly /lab/important
OUTPUT
/lab/backups/backup-2026-10-31.tar.gz
/lab/backups/backup-2026-10-25.tar.gz
/lab/backups/backup-2026-10-21.tar.gz
...
/lab/backups/monthly/backup-2026-09-19.tar.gz
...
/lab/backups/backup-2026-11-03.tar.gz
/lab/backups/monthly:

/lab/important:
backup-2025-10-14.tar.gz
  • -mtime +14 means "modified more than 14 whole days ago": 15 days or older.
  • 18 files matched, not 17. One is monthly/backup-2026-09-19.tar.gz. find searches every folder below the one you give it, so the monthly backup, kept on purpose, was old enough and matched. ls shows monthly empty: it's gone.
  • /lab/important survived, but only by luck of a default: find doesn't follow links to folders unless you ask it to (-L). Add -L to make it "see everything", and the backup from before the move goes too.
  • The list came out in no particular order. find lists files in the order the file system stores them, not by name or date. Fine for deleting, useless for "keep the newest".

The first command was the right instinct: look before you delete. The mistake was trusting a list of 18 files without reading it.

2. It deletes your last backup

Now the same rule on the second server, whose backups stopped 20 days ago, without anyone noticing:

BASH
./make-fake-backups /lab
find /lab/stopped -name "*.tar.gz" -mtime +14 -delete
echo "backups left: $(ls -A /lab/stopped | wc -l)"
OUTPUT
backups left: 0

Zero. Every backup that server had was more than 14 days old, so the rule deleted every one. The cleanup job did exactly what it was told. An age rule on its own assumes new backups keep arriving. When they stop, it carries on deleting until there's nothing left, and the day you need a backup, you find out both jobs had failed.

3. It deletes the whole folder

find reads its expression left to right, and acts as it goes. Put -delete in the wrong place:

BASH
./make-fake-backups /lab
find /lab/backups -delete -name "*.part"
ls -A /lab/backups; ls -d /lab/backups
OUTPUT
ls: cannot access '/lab/backups': No such file or directory
ls: cannot access '/lab/backups': No such file or directory

The intent was "delete the .part file". The result was "delete everything, including the folder". For each file, find ran -delete first, which deleted it, and only then checked the name. Every file went, then monthly, then backups itself. The find manual warns about exactly this. Put -delete last, always, and run the same command with -print in its place first.

4. It deletes the whole computer

A script keeps its backup folder in a variable, and deletes everything in it:

BASH
rm -rf "$DIR"/*

Here's what that becomes if DIR is empty, because a setting was misspelled, a config file didn't load, or a step before it failed. These lines use echo, so they only print the command. Never remove the echo:

BASH
DIR=""
echo rm -rf "$DIR"/*
bash -uc 'echo rm -rf "$NOPE"/*'
OUTPUT
rm -rf /bin /boot /dev /etc /home /lab /lib /media /mnt /opt /practice /proc /root /run /sbin /srv /sys /tmp /usr /var
bash: line 1: NOPE: unbound variable

An empty DIR turns "$DIR"/* into /*: every folder on the computer. Including /practice, which in this container is the practice folder on your own computer. This isn't a made-up risk: in 2015, the Linux version of the Steam game launcher shipped a script with rm -rf "$STEAMROOT/"* in it. For users who'd moved their Steam folder, STEAMROOT came out empty, and the script deleted every file on the computer that their user was allowed to delete, other drives included.

The second line shows the cheapest defense. bash -u (or set -u, part of set -euo pipefail) makes an unset variable an error, so the script stops before rm runs. It doesn't catch a variable that's set to an empty string, like DIR="" here, so a script that deletes needs one more check of its own.

A cleanup job is a shredder with the lid off. It does exactly one thing, and it does it to whatever's fed to it, without reading it first. You don't make that safer by being careful each time; you make it safer by building a machine that only accepts paper from one tray, holds each sheet up for you to see, and refuses to shred the last copy of anything.

The safe version

prune-backups in the practice folder does the same job, with a guard against each of those four mistakes:

The mistakeThe guard
Deleting more than you meantOnly regular files, directly in the folder, with a name like backup-*.tar.gz. And a dry run by default, so you see the list first.
Deleting your last backupAlways keep the newest 7, however old. And exit 1 with a warning when the newest is too old: the backups may have stopped.
Deleting in the wrong orderNo -delete at all: find only lists, and the script decides, one file at a time.
Deleting from an empty pathRefuse an empty folder name, /, system folders, your home folder, and links.

The whole script:

BASH
#!/usr/bin/env bash
# prune-backups: delete old backups from one folder, safely.
#
#   prune-backups FOLDER            show what would be deleted, and delete nothing
#   prune-backups --apply FOLDER    delete it
set -euo pipefail

KEEP=${KEEP:-7}
MAX_AGE_DAYS=${MAX_AGE_DAYS:-14}
PATTERN=${PATTERN:-backup-*.tar.gz}

log() { printf '%s prune-backups: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
refuse() { log "refusing: $*"; exit 2; }
usage() { echo "usage: prune-backups [--apply] FOLDER" >&2; exit 2; }

apply=0
if [ "${1:-}" = --apply ]; then apply=1; shift; fi
[ $# -eq 1 ] || usage
dir=$1

# Guard rails, before anything is listed, let alone deleted.
[ -n "$dir" ] || refuse "the folder is an empty string (an unset variable?)"
[[ $KEEP =~ ^[0-9]+$ ]] && [ "$KEEP" -ge 1 ] || refuse "KEEP must be 1 or more, not '$KEEP'"
[[ $MAX_AGE_DAYS =~ ^[0-9]+$ ]] || refuse "MAX_AGE_DAYS must be a number, not '$MAX_AGE_DAYS'"
[ -d "$dir" ] || refuse "$dir isn't a folder"
[ ! -L "$dir" ] || refuse "$dir is a link; give the real folder"
real=$(realpath "$dir")
case "$real" in
	/ | /bin | /boot | /dev | /etc | /home | /lib | /proc | /root | /sbin | /sys | /usr | /var | "$HOME")
		refuse "$real is a system or home folder" ;;
esac

# Every candidate, newest first: modification time, size and path, separated by
# NUL bytes so a name with a space (or a newline) arrives whole.
mapfile -d '' entries < <(
	find "$real" -mindepth 1 -maxdepth 1 -type f -name "$PATTERN" -printf '%T@ %s %p\0' | sort -z -rn
)

now=$(date +%s)
kept=0 deleted=0 freed=0 failed=0 newest_age=-1
for e in "${entries[@]}"; do
	mtime=${e%% *}; rest=${e#* }
	size=${rest%% *}; path=${rest#* }
	age=$(( (now - ${mtime%.*}) / 86400 ))
	[ "$newest_age" -ge 0 ] || newest_age=$age

	if [ "$kept" -lt "$KEEP" ]; then
		kept=$((kept + 1))
		continue
	fi
	if [ "$age" -le "$MAX_AGE_DAYS" ]; then
		kept=$((kept + 1))
		continue
	fi
	if [ "$apply" -eq 0 ]; then
		log "would delete $path ($age days old, $size bytes)"
	elif rm -f -- "$path"; then
		log "deleted $path ($age days old, $size bytes)"
	else
		log "couldn't delete $path"
		failed=$((failed + 1))
		continue
	fi
	deleted=$((deleted + 1))
	freed=$((freed + size))
done

verb=$([ "$apply" -eq 1 ] && echo "deleted" || echo "would delete")
log "$real: ${#entries[@]} backups, kept $kept, $verb $deleted ($(numfmt --to=iec "$freed"))"
[ "$apply" -eq 1 ] || log "dry run: nothing was deleted. Add --apply to delete."

status=0
if [ "${#entries[@]}" -eq 0 ]; then
	log "no backups at all in $real"
	status=1
elif [ "$newest_age" -gt 1 ]; then
	log "the newest backup is $newest_age days old: the backups may have stopped"
	status=1
fi
[ "$failed" -eq 0 ] || status=1
exit "$status"

The file in the practice folder has the same code with more comments: prune-backups on GitHub (opens in a new tab), and the script that makes the fake backups, make-fake-backups (opens in a new tab). Taking it in order:

A dry run by default

Without --apply, the script lists what it would delete, and deletes nothing. Most tools work the other way round, with a --dry-run option you have to remember. Here, forgetting means nothing happens, which is the right way round for a job that can't be undone. You run it, read the list, and only then run it again with --apply.

Guard rails, before anything else

Every check runs before find lists a single file:

  • [ -n "$dir" ]: the folder name isn't empty. This is the check set -u can't do: it catches DIR="" as well as an unset variable passed in by mistake.
  • KEEP is a whole number, at least 1. KEEP=0 would switch off the protection for the last backups, so the script refuses it. And MAX_AGE_DAYS must be a number.
  • [ -d "$dir" ]: it's a folder that exists.
  • [ ! -L "$dir" ]: it's not a link. A link can be changed to point somewhere else; the real path can't.
  • realpath then case: work out the real, full path, .. and all, and refuse /, the main system folders, and your home folder. A backup folder is never one of those, so a script that's been given one has been given the wrong thing.
  • refuse exits 2, "called wrongly or refused": the script never started the job.

Find only what you mean

BASH
find "$real" -mindepth 1 -maxdepth 1 -type f -name "$PATTERN" -printf '%T@ %s %p\0' | sort -z -rn
  • -mindepth 1 -maxdepth 1: only things directly in the folder. Not the folder itself, not monthly/ or anything else below it. This is the fix for mistake 1.
  • -type f: only regular files. Not folders, and not links: backup-latest.tar.gz and archive are links, so they're never touched, even when they're old.
  • -name "$PATTERN", backup-*.tar.gz by default: the name has to match the whole pattern. README.txt doesn't, and neither does backup-2026-11-18.tar.gz.part, which ends in .part, so a backup that's still being written is never deleted halfway through.
  • No -delete. find only lists. That rules out mistake 3 completely.
  • -printf '%T@ %s %p\0': for each file, its modification time in seconds (%T@), its size in bytes (%s) and its path (%p), ending in a NUL byte (\0) instead of a newline. A file name can contain spaces and even newlines, but never a NUL byte, so it's the one safe separator, as -print0 was in Linux Lesson 12.
  • sort -z -rn: sort those NUL-separated entries by the number at the front, biggest first: newest first.
  • mapfile -d '' entries reads them into an array, one entry per file, splitting on NUL.

The rule: keep the newest, then check age

For each file, newest first:

  1. The first KEEP (7) are kept, whatever their age. This is the fix for mistake 2: however long the backups have been stopped, the last 7 are still there.
  2. After that, a file MAX_AGE_DAYS (14) days old or younger is kept.
  3. Anything else is deleted, or listed as "would delete" in a dry run.

The age is worked out by the script: today's time minus the file's, in seconds, divided by 86,400 (the seconds in a day) and rounded down. "More than 14 days" means the same here as find's -mtime +14.

Delete one file at a time, and say so

  • rm -f -- "$path": the quotes keep a name with spaces whole. -- means "no more options", so a name starting with a dash can never be read as one. Here every path starts with /, so it can't happen, but -- costs nothing and makes the line safe to copy anywhere.
  • Every deletion is logged with its age and size, with a UTC timestamp, to standard error, as in the Linux track. After a cleanup, the log is the only record of what was there.
  • A failed delete is counted, not fatal. One file it can't delete shouldn't stop the rest, but it does change the exit code.

An exit code that means something

Exit codeMeans
0Done: deleted what it should, or there was nothing to delete
1Something's wrong: a delete failed, there are no backups at all, or the newest is more than a day old
2Called wrongly, or refused: nothing was looked at

The "backups may have stopped" check is the cleanup job doing a second job: it's the only thing that looks at the backup folder every night, so it's well placed to notice when nothing new has arrived. Exit 1 means anything that watches the job, which Lesson 2 sets up, hears about it.

Run it

Start again with fresh fake backups. The dry run first:

BASH
./make-fake-backups /lab
./prune-backups /lab/backups; echo "exit $?"
OUTPUT
2026-11-18T14:00:22Z prune-backups: would delete /lab/backups/backup-2026-11-03.tar.gz (15 days old, 187392 bytes)
2026-11-18T14:00:22Z prune-backups: would delete /lab/backups/backup-2026-11-02.tar.gz (16 days old, 242688 bytes)
...
2026-11-18T14:00:22Z prune-backups: would delete /lab/backups/backup-2026-10-24.tar.gz (25 days old, 200704 bytes)
2026-11-18T14:00:22Z prune-backups: would delete /lab/backups/backup-2026-10-24 copy.tar.gz (25 days old, 199680 bytes)
...
2026-11-18T14:00:22Z prune-backups: would delete /lab/backups/backup-2026-10-19.tar.gz (30 days old, 202752 bytes)
2026-11-18T14:00:22Z prune-backups: /lab/backups: 31 backups, kept 14, would delete 17 (3.5M)
2026-11-18T14:00:22Z prune-backups: dry run: nothing was deleted. Add --apply to delete.
exit 0
  • Newest first, oldest last, so the list reads like a timeline, and you can see exactly where it starts deleting: 15 days.
  • 31 backups: the 30 nightly ones and the copy. Not the README, not the .part file, not the links, not monthly.
  • The copy with a space in its name arrives whole, as one file, and it's old, so it's on the list.
  • Kept 14: the newest 7, plus the 7 more that are 14 days old or younger.

The list is right, so apply it, then run it again:

BASH
./prune-backups --apply /lab/backups; echo "exit $?"
./prune-backups --apply /lab/backups; echo "exit $?"
ls -A /lab/backups /lab/backups/monthly /lab/important
OUTPUT
2026-11-18T14:00:22Z prune-backups: deleted /lab/backups/backup-2026-11-03.tar.gz (15 days old, 187392 bytes)
...
2026-11-18T14:00:22Z prune-backups: deleted /lab/backups/backup-2026-10-19.tar.gz (30 days old, 202752 bytes)
2026-11-18T14:00:22Z prune-backups: /lab/backups: 31 backups, kept 14, deleted 17 (3.5M)
exit 0
2026-11-18T14:00:22Z prune-backups: /lab/backups: 14 backups, kept 14, deleted 0 (0)
exit 0
/lab/backups:
README.txt  backup-2026-11-04.tar.gz  backup-2026-11-06.tar.gz  backup-2026-11-08.tar.gz  backup-2026-11-10.tar.gz  backup-2026-11-12.tar.gz  backup-2026-11-14.tar.gz  backup-2026-11-16.tar.gz  backup-2026-11-18.tar.gz.part  monthly
archive     backup-2026-11-05.tar.gz  backup-2026-11-07.tar.gz  backup-2026-11-09.tar.gz  backup-2026-11-11.tar.gz  backup-2026-11-13.tar.gz  backup-2026-11-15.tar.gz  backup-2026-11-17.tar.gz  backup-latest.tar.gz

/lab/backups/monthly:
backup-2026-09-19.tar.gz

/lab/important:
backup-2025-10-14.tar.gz
  • The same 17 files the dry run listed, and nothing else. That's the point of a dry run: what you read is what happens.
  • The second run deleted nothing, because there was nothing left to delete. Safe to run twice, so safe to rerun after a failure without thinking about it.
  • Everything that should survive did: 14 backups, the README, the .part file, both links, the monthly backup and the one in important.

The server whose backups stopped

BASH
./prune-backups --apply /lab/stopped; echo "exit $?"
OUTPUT
2026-11-18T14:00:22Z prune-backups: deleted /lab/stopped/backup-2026-10-22.tar.gz (27 days old, 209920 bytes)
2026-11-18T14:00:22Z prune-backups: deleted /lab/stopped/backup-2026-10-21.tar.gz (28 days old, 218112 bytes)
2026-11-18T14:00:22Z prune-backups: deleted /lab/stopped/backup-2026-10-20.tar.gz (29 days old, 191488 bytes)
2026-11-18T14:00:22Z prune-backups: /lab/stopped: 10 backups, kept 7, deleted 3 (605K)
2026-11-18T14:00:22Z prune-backups: the newest backup is 20 days old: the backups may have stopped
exit 1

Where the obvious rule left 0 backups, this one left 7, and said why something's wrong. All ten were older than 14 days, so the age rule alone would have taken them all; the keep rule saved the newest 7. And exit 1 means the next lesson's monitoring will hear about it the first night, not three weeks later.

Which backups the rule keepsTwo rows of backups, laid out by age in days. On the healthy server, with one backup a night for 30 nights, the newest 7 are always kept, the 7 that are 8 to 14 days old are kept by the age rule, and the 16 older than 14 days are deleted, with the hand-made copy that's 17. On the stopped server, whose backups are 20 to 29 days old, the newest 7 are kept even though all are past the age limit, and only the 3 oldest are deleted. The age rule alone would delete all ten.Healthy server: one backup a nightnewest 7: always kept8 to 14 days: keptover 14 days: deleted (17, with the copy)14 daysStopped server: backups ended 20 days agonewest 7: kept, however olddeletedno new backups for 20 days: exit 11 day old7142030 days old
The real run, laid out by age. Filled boxes are kept because they're among the newest 7; tinted ones are kept by the age rule; dashed ones are deleted. The age rule alone would have deleted every backup on the stopped server.

What it refuses to do

The guard rails, tested on purpose:

BASH
./prune-backups /; echo "exit $?"
./prune-backups "$NOPE"; echo "exit $?"
./prune-backups; echo "exit $?"
KEEP=0 ./prune-backups /lab/backups; echo "exit $?"
./prune-backups /lab/backups/archive; echo "exit $?"
OUTPUT
2026-11-18T14:00:29Z prune-backups: refusing: / is a system or home folder
exit 2
2026-11-18T14:00:29Z prune-backups: refusing: the folder is an empty string (an unset variable?)
exit 2
usage: prune-backups [--apply] FOLDER
exit 2
2026-11-18T14:00:29Z prune-backups: refusing: KEEP must be 1 or more, not '0'
exit 2
2026-11-18T14:00:29Z prune-backups: refusing: /lab/backups/archive is a link; give the real folder
exit 2
  • /: refused by the system-folder list.
  • "$NOPE", an unset variable: the shell turns it into an empty string, and the script refuses that. This is mistake 4 again, from the outside: the Steam bug would have stopped here.
  • No folder at all: the usage line.
  • KEEP=0: refused, because it would switch off the last-backups protection.
  • The link archive: refused, so the script can't be pointed at a folder through a link it doesn't control.

These are dry runs, and they were still refused. A guard rail that only works with --apply is one you haven't tested.

Clean up

BASH
exit

exit leaves the container, and --rm deletes it, with /lab and everything in it. Nothing in the practice folder on your computer was deleted.

On a real server

  • Run the dry run by hand first, on the real folder, and read every line, before you schedule --apply.
  • Run it as the user that owns the backups, not root. Then the worst a mistake can do is limited to what that user can delete.
  • Choose KEEP and MAX_AGE_DAYS from how you restore, not how much space you have: how far back might you need to go, and how many good copies do you want if the newest few are bad?
  • Keep a copy somewhere else. This script protects you from deleting too much. It doesn't protect you from losing the disk. Lesson 2 copies the backups off the server.
  • Watch the exit code. Exit 1 here can mean "your backups stopped", the most important thing this job will ever tell you. Lesson 2 makes sure someone hears it.
  • Try shellcheck on any script that deletes. It catches unquoted variables, the mistake behind most of these stories.

Spot the problem

Work out what's wrong before you read the explanation.

"Some of my files are missing." A server has had this line in its crontab for two years:

BASH
0 3 * * * cd /srv/backups; find . -name "*.tar.gz" -mtime +14 -delete

Last week, someone renamed /srv/backups to /srv/db-backups, and updated the backup job, but not this line. A week later, a developer on the server finds that every .tar.gz older than two weeks in their home folder is gone: project archives, downloads, a copy of last year's data. What happened? cd /srv/backups failed, because the folder doesn't exist any more, and ; runs the next command anyway. cron runs jobs in the user's home folder, so find . searched there, and deleted everything that matched. The fix: never let a delete run somewhere you didn't choose. Use && (cd /srv/backups && find ...), or better, give find the full path and no cd at all, as prune-backups does, which also refuses a folder that doesn't exist. Then check: point it at a folder that doesn't exist, in a dry run, and confirm it refuses.

Keep this

ToUse
Make a file look oldtouch -d "20 days ago" FILE
List files more than 14 days oldfind DIR -type f -mtime +14
Only look in one folder, not below itfind DIR -mindepth 1 -maxdepth 1
Only regular files, not links or foldersfind ... -type f
Delete with find, safelyRun it with -print first, and put -delete last
Time, size and path of each filefind ... -printf '%T@ %s %p\0'
Newest first, NUL-separatedsort -z -rn
Read NUL-separated lines into an arraymapfile -d '' ARRAY
Stop on an unset variableset -u, or bash -u
Refuse an empty one[ -n "$VAR" ] || exit 2
The real, full pathrealpath PATH
Delete a file whose name might start with a dashrm -f -- "$FILE"
Bytes to a readable sizenumfmt --to=iec BYTES

Where you are now

You've seen the obvious cleanup job delete a monthly backup it was never meant to see, every backup on a server whose backups had stopped, a whole folder because of where one word sat, and very nearly a whole computer because of an empty variable. And you've built one that does none of those: it shows you the list before it deletes, only touches the files it's meant to, always keeps the newest, refuses the paths it should never be given, and says when something's wrong. Lesson 2 runs it every night on a server, alongside the backup itself, and makes sure that when either one stops, you find out.

Check yourself

  1. Why did the obvious find command delete the monthly backup?

  2. A server's backups stopped 20 days ago. What does 'delete backups older than 14 days' leave?

  3. What does find /lab/backups -delete -name '*.part' delete?

  4. DIR is an empty string. What does rm -rf $DIR/* become, quotes and all?

  5. Why does prune-backups list files with -printf ... \0 and not print one per line?

  6. The script exits 1 with 'the newest backup is 20 days old'. What should happen next?

Key terms

  • Retention: how long, or how many, backups you keep before deleting them.
  • Dry run: a run that shows what it would do, and changes nothing. Here it's the default.
  • Guard rail: a check that stops a script before it does something it should never do, like deleting from /.
  • Modification time: when a file's contents last changed; find -mtime and touch -d both work with it.
  • NUL byte: the byte with value zero, the one character a file name can't contain, so the safe separator between names.
  • Idempotent: safe to run again; a second run with nothing to do changes nothing.
  • Exit code: the number a program ends with; here 0 for done, 1 for something wrong, 2 for refused.

Go deeper