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 ... -deletegoes 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
findfrom Linux Lesson 3 and Lesson 12, andset -euo pipefailfrom 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:
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:
hostname; pwd; ls
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)
./make-fake-backups /lab
ls -lA --time-style=+%F /lab/backups
du -sh /lab/backups
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:
| Option | Means | Example |
|---|---|---|
-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 +N | Last changed more than N whole days ago. The + means "more than". | -mtime +14: 15 days old or older |
-mtime N | Last changed exactly N whole days ago | -mtime 14: 14 days old |
-mtime -N | Last changed fewer than N whole days ago. The - means "less than". | -mtime -14: 0 to 13 days old |
-type f | Only regular files: not folders (d), not links (l) | Skips monthly/ and backup-latest.tar.gz |
-maxdepth 1 | Don't look in folders below this one | Skips monthly/backup-2026-09-19.tar.gz |
-mindepth 1 | Don't include the starting folder itself | Never lists /lab/backups as a result |
-print | Print 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 |
-delete | Delete each match, at the point it appears in the line | Always 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 byte | Used 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:
find /lab/backups -name "*.tar.gz" -mtime +14
find /lab/backups -name "*.tar.gz" -mtime +14 -delete
ls -A /lab/backups/monthly /lab/important
/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 +14means "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.findsearches every folder below the one you give it, so the monthly backup, kept on purpose, was old enough and matched.lsshowsmonthlyempty: it's gone. /lab/importantsurvived, but only by luck of a default:finddoesn't follow links to folders unless you ask it to (-L). Add-Lto make it "see everything", and the backup from before the move goes too.- The list came out in no particular order.
findlists 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:
./make-fake-backups /lab
find /lab/stopped -name "*.tar.gz" -mtime +14 -delete
echo "backups left: $(ls -A /lab/stopped | wc -l)"
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:
./make-fake-backups /lab
find /lab/backups -delete -name "*.part"
ls -A /lab/backups; ls -d /lab/backups
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:
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:
DIR=""
echo rm -rf "$DIR"/*
bash -uc 'echo rm -rf "$NOPE"/*'
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.
The safe version
prune-backups in the practice folder does the same job, with a guard against each of those four mistakes:
| The mistake | The guard |
|---|---|
| Deleting more than you meant | Only 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 backup | Always 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 order | No -delete at all: find only lists, and the script decides, one file at a time. |
| Deleting from an empty path | Refuse an empty folder name, /, system folders, your home folder, and links. |
The whole script:
#!/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 checkset -ucan't do: it catchesDIR=""as well as an unset variable passed in by mistake.KEEPis a whole number, at least 1.KEEP=0would switch off the protection for the last backups, so the script refuses it. AndMAX_AGE_DAYSmust 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.realpaththencase: 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.refuseexits 2, "called wrongly or refused": the script never started the job.
Find only what you mean
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, notmonthly/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.gzandarchiveare links, so they're never touched, even when they're old.-name "$PATTERN",backup-*.tar.gzby default: the name has to match the whole pattern.README.txtdoesn't, and neither doesbackup-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.findonly 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-print0was in Linux Lesson 12.sort -z -rn: sort those NUL-separated entries by the number at the front, biggest first: newest first.mapfile -d '' entriesreads them into an array, one entry per file, splitting on NUL.
The rule: keep the newest, then check age
For each file, newest first:
- 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. - After that, a file
MAX_AGE_DAYS(14) days old or younger is kept. - 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 code | Means |
|---|---|
0 | Done: deleted what it should, or there was nothing to delete |
1 | Something's wrong: a delete failed, there are no backups at all, or the newest is more than a day old |
2 | Called 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:
./make-fake-backups /lab
./prune-backups /lab/backups; echo "exit $?"
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
.partfile, not the links, notmonthly. - 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:
./prune-backups --apply /lab/backups; echo "exit $?"
./prune-backups --apply /lab/backups; echo "exit $?"
ls -A /lab/backups /lab/backups/monthly /lab/important
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
.partfile, both links, the monthly backup and the one inimportant.
The server whose backups stopped
./prune-backups --apply /lab/stopped; echo "exit $?"
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.
What it refuses to do
The guard rails, tested on purpose:
./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 $?"
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
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
KEEPandMAX_AGE_DAYSfrom 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
shellcheckon 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:
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
| To | Use |
|---|---|
| Make a file look old | touch -d "20 days ago" FILE |
| List files more than 14 days old | find DIR -type f -mtime +14 |
| Only look in one folder, not below it | find DIR -mindepth 1 -maxdepth 1 |
| Only regular files, not links or folders | find ... -type f |
| Delete with find, safely | Run it with -print first, and put -delete last |
| Time, size and path of each file | find ... -printf '%T@ %s %p\0' |
| Newest first, NUL-separated | sort -z -rn |
| Read NUL-separated lines into an array | mapfile -d '' ARRAY |
| Stop on an unset variable | set -u, or bash -u |
| Refuse an empty one | [ -n "$VAR" ] || exit 2 |
| The real, full path | realpath PATH |
| Delete a file whose name might start with a dash | rm -f -- "$FILE" |
| Bytes to a readable size | numfmt --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
Why did the obvious find command delete the monthly backup?
A server's backups stopped 20 days ago. What does 'delete backups older than 14 days' leave?
What does find /lab/backups -delete -name '*.part' delete?
DIR is an empty string. What does rm -rf $DIR/* become, quotes and all?
Why does prune-backups list files with -printf ... \0 and not print one per line?
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 -mtimeandtouch -dboth 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
- Earlier lessons: Reading and searching files for
find, Loops, conditions and one-liners for-print0and names with spaces, and Shell scripts and cron, done properly forset -euo pipefailand cron. - Manuals:
man find(look for-deleteand its warning),man touchandman realpath, in the container or on any Linux machine. - The Steam for Linux bug report (opens in a new tab), where the empty-variable
rm -rfwas found in 2015. - BashPitfalls (opens in a new tab), a long list of the mistakes that make shell scripts do the wrong thing, many of them about quoting.
- ShellCheck (opens in a new tab), which reads a script and points out mistakes like unquoted variables.
- Try: run
prune-backupswithKEEP=3 MAX_AGE_DAYS=7and predict the summary line before you look. Then make an old backup with a newline in its name,touch -d "20 days ago" $'/lab/backups/backup-new\nline.tar.gz', and run the dry run. Its log line breaks in two, but the summary should count 32 backups: one file, whole.