$_ CLI In Depth
Learning progress 0%
build packages services cron

Build: A Scheduled Backup Rotator

4 min read Module 11: Packages, Services & Scheduled Jobs Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:06

The specification

Write a script named rotate.sh in /workspace. It takes three arguments: the source directory to back up, the destination directory that holds the archives, and the number of archives to keep. Each run creates one new gzip-compressed tar archive in the destination, named with a time stamp that includes nanoseconds, so two runs in the same second do not overwrite each other. After the new archive is written, the script keeps the newest N archives and deletes the older ones.

The script must check its arguments and exit with status 2 when they are missing. It must exit with a nonzero status if the archive cannot be written, and it must not delete anything in that case. Those two rules protect the existing backups when something goes wrong.

Design decisions

The name carries the time, so the newest archive is also the last one in a sorted list. Sorting by name is therefore enough to decide which archives are old, and the script needs no database. The nanoseconds field keeps the names unique even for rapid runs. A GNU date that supports the N format is needed for this, which the lab provides.

Deleting is the risky step, so the script creates the new archive first and deletes only after tar has returned success. If tar fails, the script exits before the deletion loop, and every older backup stays in place. This ordering is the most important property of the design.

Reference solution

The reference below is one way to meet the specification. It is short enough to read in one pass, and each block corresponds to a rule above.

BASH12 lines
#!/bin/bash
# usage: rotate.sh SOURCE_DIR DEST_DIR KEEP
if [ "$#" -ne 3 ]; then echo "usage: rotate.sh SOURCE DEST KEEP" >&2; exit 2; fi
src=$1; dest=$2; keep=$3
mkdir -p "$dest" || exit 1
name="backup-$(date +%Y%m%d-%H%M%S-%N).tar.gz"
tar -czf "$dest/$name" -C "$src" . || exit 1
i=0
for f in $(ls -1 "$dest"/backup-*.tar.gz | sort -r); do
  i=$((i + 1))
  if [ "$i" -gt "$keep" ]; then rm -f -- "$f"; fi
done

The first block checks the argument count and exits with status 2 when it is wrong. The second block creates the destination and writes the archive, and it stops with status 1 if either step fails, before any deletion. The loop sorts the archive names in reverse, so the newest comes first, and it removes every archive after the first N.

Warning

The loop relies on archive names without spaces, which the time-stamp format guarantees. If you change the naming scheme, test the loop with a name that contains a space before you schedule the script.

Scheduling the rotator

To run the rotator every night, add a crontab line that calls it with full paths and a log file, as the cron units described. The line runs at 03:00 and keeps the newest seven archives. Write the line and read it back, but do not install it in this lab, because the lab has no cron daemon.

BASH1 lines
0 3 * * * /workspace/rotate.sh /workspace/data /workspace/backups 7 >> /workspace/rotate.log 2>&1

Testing the rotator

Test the script on a small source directory first. Run it several times, with a short pause between runs so the time stamps differ, and count the archives in the destination. With a keep value of 2, three runs should leave exactly two archives. Then run it once with the wrong number of arguments and confirm that it exits with status 2 and deletes nothing.

BASH5 lines
mkdir -p src && echo data > src/a.txt
bash rotate.sh src backups 2; sleep 1
bash rotate.sh src backups 2; sleep 1
bash rotate.sh src backups 2
ls backups | wc -l

The final count is 2. The checks in the lab repeat this test in a fresh directory, so the number of archives is the signal that the rotation works.

Extensions to consider

A production rotator would verify each archive with tar -tzf before deleting old ones, write its log lines with a time stamp, and refuse to run if another copy is already active. Each of these is a small addition, and each one should be tested with the same counting method as the base version.

Hands-on: write and run the rotator

Create rotate.sh with the reference logic, prepare the source directory, and run the rotator three times with keep set to 2. Then count the archives. The lab checks the count and the script, so the count must be exactly two.

Terminal lab · 2 steps · real Linux in your browser

Build and run a backup rotator

Write rotate.sh to the spec, then run it three times and check that only the newest two archives remain.

01
Write rotate.sh to the spec
Create rotate.sh in /workspace. It takes a source directory, a destination directory, and a keep count. It creates a time-stamped gzip tar archive, and it deletes archives beyond the keep count only after tar succeeds. Write it with a heredoc, using the reference logic from the unit. ``bash cat > rotate.sh <<'EOF' #!/bin/bash if [ "$#" -ne 3 ]; then echo "usage: rotate.sh SOURCE DEST KEEP" >&2; exit 2; fi src=$1; dest=$2; keep=$3 mkdir -p "$dest" || exit 1 name="backup-$(date +%Y%m%d-%H%M%S-%N).tar.gz" tar -czf "$dest/$name" -C "$src" . || exit 1 i=0 for f in $(ls -1 "$dest"/backup-*.tar.gz | sort -r); do i=$((i + 1)) if [ "$i" -gt "$keep" ]; then rm -f -- "$f"; fi done EOF ``
Show hint for step 1
The name must include %N. The deletion loop must run after the tar line, so a failed tar leaves the old archives alone.
02
Run three backups and keep two
Create a source directory named src with one file in it. Run rotate.sh three times with keep set to 2, with a one-second pause between runs, so that the archives get different names. Then count the archives in backups. ``bash mkdir -p src && echo data > src/a.txt bash rotate.sh src backups 2; sleep 1 bash rotate.sh src backups 2; sleep 1 bash rotate.sh src backups 2 ls backups | wc -l `` The count printed at the end should be 2.
Show hint for step 2
Use the same keep value for all three runs. The pause makes the time stamps differ.
Check yourself Question 1 of 4
Concept Check Wrong argument count recall

What exit status does the reference rotate.sh return when it is given the wrong number of arguments?

Recap & Key Takeaways

The rotator creates the new archive first, and it deletes older archives only after tar returns success.
Time-stamped archive names sort chronologically, so sorting in reverse finds the newest N without a database.
Check the argument count and exit with status 2 when it is wrong, so the script never deletes with bad input.
Test a rotator with repeated runs and a count of the results before you schedule it.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue