Build a Timestamped Backup Script
This project builds backup.sh, a backup tool you can run by hand or from cron. Each run packs one or more directories into a compressed archive named after the moment it was made, such as projects-20261202-170629.tar.gz, checks that the archive is readable, writes a SHA-256 checksum next to it, logs every step, and deletes the oldest backups so that only the newest N are kept.
Lesson 164 introduced the basic idea of backing up with tar. This project turns that idea into a tool that is safe to leave running unattended. The difference lies in the questions a production script must answer: What happens if two runs overlap? If the disk fills up halfway through? If someone presses Ctrl+C? If an exclude pattern accidentally excludes everything? How do you know, months later, that a backup file has not been silently corrupted?
What the Script Should Do
- Archive one or more directories or files into
DEST/NAME-YYYYMMDD-HHMMSS.tar.gz. - Store relative paths in the archive (
projects/site/index.html, not/home/user/projects/site/index.html), so it can be restored anywhere. - Exclude unwanted content, such as
node_modules, caches and log files, from a pattern file. - Never leave a broken archive behind under a real backup name, even if the script is interrupted or the disk fills up.
- Verify the archive before accepting it, and record a checksum for later checks.
- Rotate: keep the newest
KEEPbackups of each name and delete older ones. - Prevent overlapping runs that write to the same destination.
- Log every step with a time stamp, and exit with a status that cron or a monitoring tool can act on.
Design Decisions
Time Stamps That Sort Correctly
The backup name uses the format %Y%m%d-%H%M%S: year, month, day, hour, minute, second, each padded with zeros. Because the most significant part comes first and every field has a fixed width, sorting the names alphabetically also sorts them by time:
projects-20261130-020000.tar.gz
projects-20261201-020000.tar.gz
projects-20261202-020000.tar.gz
A format like 2-12-2026 would sort 10-1-2026 before 2-1-2026, and the rotation logic would delete the wrong files. This property lets the script find the oldest backups without parsing dates at all.
Relative Paths with tar -C
If you run tar -czf backup.tar.gz /home/suriya/projects, GNU tar strips the leading / but still stores home/suriya/projects/.... Restoring then recreates the whole home/suriya structure. The -C DIR option makes tar change into DIR before adding the following names, so each source is split into its parent directory and its last component:
abs=$(cd -- "$src" && pwd -P) # /home/suriya/projects
tar_sources+=(-C "${abs%/*}/" "${abs##*/}") # -C /home/suriya/ projects
cd ... && pwd -Pturns a relative path like../projectsinto an absolute one, with symbolic links resolved. It runs inside$( ), a subshell, so the script's own working directory does not change.${abs%/*}removes the last/and everything after it, giving the parent directory. The extra/at the end makes the result/instead of an empty string for a top-level directory like/etc.${abs##*/}keeps only the last component.
-C can appear several times in one tar command, each one applying to the names after it, so the array can hold any number of sources from different places:
tar --create --gzip --file X -C /home/suriya/projects/ notes -C /home/suriya/ settings.conf
A single file is handled the same way, except that cd goes into the file's directory. Backing up / itself is refused: it would produce an archive of the entire system, including the destination directory, which is almost never what someone means.
The sources are collected in a Bash array (lesson 97) and passed as "${tar_sources[@]}". Each element stays one argument, so directory names with spaces work without any extra quoting.
Excluding Content
tar --exclude-from FILE reads one pattern per line. A pattern without a slash matches a name at any depth:
node_modules
*.log
.cache
Excludes have a dangerous failure mode: a pattern like * excludes everything, and tar happily creates a valid archive containing nothing. The script counts the entries in the archive and refuses an empty backup, so that mistake is noticed on the first run instead of on the day a restore is needed.
Writing to a Temporary Name First
A backup that is half written, because the disk filled up, the machine shut down or someone pressed Ctrl+C, must never look like a finished backup. The script therefore writes to NAME-STAMP.tar.gz.partial, verifies it, and only then renames it:
mv -- "$partial" "$archive"
Within one file system, mv is a rename: the file's directory entry changes in a single atomic step, and no reader ever sees a partly renamed file. A file with the final name therefore always contains a complete, verified archive.
An EXIT trap (lessons 123 and 124) removes the partial file whenever the script ends before the rename, whatever the reason:
cleanup() {
[[ -n $partial && -e $partial ]] && rm -f -- "$partial"
return 0
}
trap cleanup EXIT
trap 'die "interrupted"' INT TERM
After the rename, partial is set to an empty string, so the trap has nothing left to remove. The INT and TERM traps call die, which logs the interruption and exits with status 1; the exit then runs the EXIT trap. The explicit return 0 matters because the && list returns 1 when there is no partial file, and an exit trap's last status could otherwise affect the script's exit status.
Verifying the Archive
Two checks run before the archive is accepted:
gzip -t -- "$partial" || die "compressed data is corrupt"
entries=$(tar --list --gzip --file "$partial" | wc -l) || die "archive cannot be listed"
(( entries > 0 )) || die "archive is empty (check the exclude patterns)"
gzip -t decompresses the whole file without writing the result anywhere and checks gzip's built-in CRC, catching truncated or damaged data. Listing the archive with tar --list checks the tar structure itself. Because of set -o pipefail, a failing tar makes the whole pipeline fail even though wc succeeds.
Checksums for Later
A backup can rot on disk long after it was verified: bad sectors, a faulty copy to another server, or a careless edit. sha256sum records a fingerprint at creation time:
( cd -- "$dest" && sha256sum -- "${archive##*/}" > "${archive##*/}.sha256" )
The command runs in a subshell inside the destination so that the checksum file contains only the file name, not the full path. That makes the pair portable: copy both files anywhere and sha256sum -c still finds the archive next to its checksum file.
Understanding tar's Exit Codes
GNU tar uses three exit statuses, and the script treats them differently:
| Status | Meaning | Script's reaction |
|---|---|---|
| 0 | Success | Continue |
| 1 | Some files changed while being read | Log a warning and continue |
| 2 | Fatal error (unreadable source, write error, disk full) | Stop with an error |
Status 1 is common when backing up live data such as a log file being written. The archive is still usable, but the changing file may be inconsistent, so it is worth a warning in the log rather than a failed backup. With set -e active, the script captures the status with tar ... || rc=$?, which keeps a non-zero status from ending the script before the case statement can look at it.
One Run at a Time with flock
If a backup takes longer than expected and cron starts the next one, two runs would write to and delete from the same directory. flock (lesson 171) prevents this:
exec 9> "$dest/.backup.lock"
flock -n 9 || die "another backup is already writing to $dest" 3
exec 9> FILE opens the lock file on file descriptor 9 for the rest of the script. flock -n 9 takes an exclusive lock on it or fails immediately (-n, non-blocking) if another process holds it. The kernel releases the lock automatically when the process exits, even after a crash or kill -9, so there are no stale lock files to clean up. The lock file itself stays in place, empty and harmless.
Rotation Without Touching Other Backups
Rotation must only consider backups of the same name. A loose pattern like projects-*.tar.gz would also match projects-old-20261202-170628.tar.gz and delete another job's backups. The script spells out the exact shape of the time stamp in the glob:
shopt -s nullglob
backups=( "$dest/$name"-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9].tar.gz )
shopt -u nullglob
- The name part is quoted, so characters in it are matched literally; the bracket expressions after it are not quoted, so they act as patterns.
nullglobmakes a pattern with no matches expand to nothing instead of to the pattern itself (lesson 149).- Bash sorts glob results, and because of the time stamp format the first elements are the oldest.
If there are more backups than KEEP, the loop deletes the first count - KEEP of them together with their checksum files. The .partial file of a running backup never matches, because the pattern ends in .tar.gz.
Validating Input Early
Every argument is checked before anything is written: KEEP must be a whole number, the name may only contain letters, digits, ., _ and - (it becomes part of a file name and of a glob pattern), every source must exist, and the exclude file must be readable. Usage errors exit with status 2, failed backups with 1 and a held lock with 3, so a caller can tell "fix the command" from "the backup failed" from "try again later".
The Complete Script
#!/usr/bin/env bash
#
# backup.sh - create a timestamped, verified .tar.gz backup and keep the newest N
#
# Usage: backup.sh -d DEST [-n NAME] [-k KEEP] [-x EXCLUDE_FILE] SOURCE...
#
# Options:
# -d DEST directory that holds the backups (created if missing)
# -n NAME backup name prefix (default: name of the first SOURCE)
# -k KEEP number of backups to keep for NAME (default: 7, 0 = keep all)
# -x EXCLUDE_FILE file with one tar exclude pattern per line
# -h show this help
#
# Creates DEST/NAME-YYYYMMDD-HHMMSS.tar.gz and a matching .sha256 file, and
# appends a line for every step to DEST/backup.log.
#
# Exit status: 0 success, 1 backup failed, 2 usage error, 3 another backup is running.
set -euo pipefail
readonly PROG=${0##*/}
dest="" name="" keep=7 exclude_file=""
partial=""
logfile=/dev/null
usage() {
sed -n '3,18s/^# \{0,1\}//p' "$0"
}
log() {
printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" | tee -a "$logfile" >&2
}
die() { # die MESSAGE [STATUS]
log "ERROR: $1"
exit "${2:-1}"
}
cleanup() {
# remove a half-written archive if the script stops before the final rename
[[ -n $partial && -e $partial ]] && rm -f -- "$partial"
return 0
}
# --- options ------------------------------------------------------------------
while getopts ':d:n:k:x:h' opt; do
case $opt in
d) dest=$OPTARG ;;
n) name=$OPTARG ;;
k) keep=$OPTARG ;;
x) exclude_file=$OPTARG ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value (try -h)" 2 ;;
*) die "unknown option -$OPTARG (try -h)" 2 ;;
esac
done
shift $((OPTIND - 1))
(( $# > 0 )) || die "no SOURCE given (try -h)" 2
[[ -n $dest ]] || die "the destination -d DEST is required (try -h)" 2
[[ $keep =~ ^[0-9]+$ ]] || die "KEEP must be a whole number, got '$keep'" 2
if [[ -n $exclude_file && ! -r $exclude_file ]]; then
die "cannot read exclude file: $exclude_file" 2
fi
# Resolve every source to an absolute path and split it into parent + entry,
# so the archive contains "projects/..." instead of "/home/user/projects/...".
tar_sources=()
for src in "$@"; do
[[ -d $src || -f $src ]] || die "source not found: $src" 2
if [[ -d $src ]]; then
abs=$(cd -- "$src" && pwd -P)
else
abs=$(cd -- "$(dirname -- "$src")" && pwd -P)/$(basename -- "$src")
fi
[[ $abs != / ]] || die "refusing to back up the whole file system" 2
tar_sources+=(-C "${abs%/*}/" "${abs##*/}")
done
[[ -n $name ]] || name=${tar_sources[2]}
[[ $name =~ ^[A-Za-z0-9._-]+$ ]] || die "NAME may only contain letters, digits, '.', '_' and '-'" 2
mkdir -p -- "$dest"
dest=$(cd -- "$dest" && pwd -P)
logfile=$dest/backup.log
# --- one backup at a time -------------------------------------------------------
exec 9> "$dest/.backup.lock"
flock -n 9 || die "another backup is already writing to $dest" 3
trap cleanup EXIT
trap 'die "interrupted"' INT TERM
# --- create the archive -----------------------------------------------------------
stamp=$(date +%Y%m%d-%H%M%S)
archive=$dest/$name-$stamp.tar.gz
partial=$archive.partial
[[ ! -e $archive ]] || die "$archive already exists" 1
tar_options=(--create --gzip --file "$partial")
[[ -n $exclude_file ]] && tar_options+=(--exclude-from "$exclude_file")
log "starting backup '$name' of: $*"
rc=0
tar "${tar_options[@]}" "${tar_sources[@]}" || rc=$?
case $rc in
0) ;;
1) log "WARNING: some files changed while they were being archived" ;;
*) die "tar failed with status $rc" ;;
esac
# --- verify before accepting it -------------------------------------------------------
gzip -t -- "$partial" || die "compressed data is corrupt"
entries=$(tar --list --gzip --file "$partial" | wc -l) || die "archive cannot be listed"
(( entries > 0 )) || die "archive is empty (check the exclude patterns)"
mv -- "$partial" "$archive"
partial=""
( cd -- "$dest" && sha256sum -- "${archive##*/}" > "${archive##*/}.sha256" )
size=$(du -h -- "$archive" | cut -f1)
log "created ${archive##*/} ($size, $entries entries)"
# --- retention: keep the newest $keep backups of this name ----------------------------
if (( keep > 0 )); then
shopt -s nullglob
# an exact pattern, so that NAME "web" never matches the backups of "web-old"
backups=( "$dest/$name"-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9].tar.gz )
shopt -u nullglob
# glob results are sorted, and the time stamps sort in time order
excess=$(( ${#backups[@]} - keep ))
for (( i = 0; i < excess; i++ )); do
rm -f -- "${backups[i]}" "${backups[i]}.sha256"
log "removed old backup ${backups[i]##*/}"
done
fi
log "backup '$name' finished"
The log function prints each message with a time stamp to standard error and, through tee -a, appends it to DEST/backup.log. Before the destination is known, logfile is /dev/null, so early usage errors are shown on the terminal only. die logs before exiting, so failures appear in the same log as successes.
Running the Script
A Test Project
mkdir -p home/projects/{site,notes} home/projects/site/node_modules/pkg home/projects/site/.cache
echo hello > home/projects/site/index.html
echo 'body{}' > home/projects/site/style.css
echo debug > home/projects/site/app.log
echo todo > home/projects/notes/todo.md
echo x > home/projects/site/node_modules/pkg/index.js
echo c > home/projects/site/.cache/c
echo conf > home/settings.conf
printf '%s\n' 'node_modules' '*.log' '.cache' > excludes.txt
The First Backup
$ ./backup.sh -d backups -x excludes.txt home/projects
2026-12-02 17:06:20 starting backup 'projects' of: home/projects
2026-12-02 17:06:20 created projects-20261202-170620.tar.gz (4.0K, 6 entries)
2026-12-02 17:06:20 backup 'projects' finished
$ ls backups
backup.log projects-20261202-170620.tar.gz projects-20261202-170620.tar.gz.sha256
$ tar -tzf backups/projects-20261202-170620.tar.gz
projects/
projects/notes/
projects/notes/todo.md
projects/site/
projects/site/style.css
projects/site/index.html
The archive starts at projects/, and node_modules, .cache and app.log are not in it. The six entries are every directory and file tar stored: three directories and three files. The checksum file contains the hash and the bare file name:
$ cat backups/projects-20261202-170620.tar.gz.sha256
e9fa65f5a4f1ffe3282833548384eb46ae11c0906479bd2361a8c30f2dd5182b projects-20261202-170620.tar.gz
$ (cd backups && sha256sum -c projects-20261202-170620.tar.gz.sha256)
projects-20261202-170620.tar.gz: OK
Your hash will differ: the archive contains file modification times, which are different on every machine.
Rotation
After several runs with -k 3, only the three newest projects backups remain. The log shows the rotation step:
$ ./backup.sh -d backups -x excludes.txt -k 3 home/projects
2026-12-02 17:06:29 starting backup 'projects' of: home/projects
2026-12-02 17:06:29 created projects-20261202-170629.tar.gz (4.0K, 6 entries)
2026-12-02 17:06:29 removed old backup projects-20261202-170624.tar.gz
2026-12-02 17:06:29 backup 'projects' finished
$ ls backups
backup.log
projects-20261202-170625.tar.gz
projects-20261202-170625.tar.gz.sha256
projects-20261202-170626.tar.gz
projects-20261202-170626.tar.gz.sha256
projects-20261202-170629.tar.gz
projects-20261202-170629.tar.gz.sha256
projects-old-20261202-170628.tar.gz
projects-old-20261202-170628.tar.gz.sha256
projects-old-20261202-170628.tar.gz, a backup made with -n projects-old in the same directory, survived, because the exact time stamp pattern does not match it.
Several Sources in One Archive
With more than one source, -n gives the backup a meaningful name. Each source appears at the top level of the archive:
$ ./backup.sh -d backups2 -n laptop home/projects/notes home/settings.conf
...
2026-12-02 17:06:35 created laptop-20261202-170635.tar.gz (4.0K, 3 entries)
...
$ tar -tzf backups2/laptop-20261202-170635.tar.gz
notes/
notes/todo.md
settings.conf
Restoring and Checking a Backup
Restoring is a matter of verifying the checksum and extracting into a directory of your choice. Comparing the result with the source using diff -r shows exactly what the excludes left out:
$ (cd backups && sha256sum -c projects-20261202-170629.tar.gz.sha256)
projects-20261202-170629.tar.gz: OK
$ mkdir restore
$ tar -xzf backups/projects-20261202-170629.tar.gz -C restore
$ diff -r restore/projects home/projects
Only in home/projects/site: .cache
Only in home/projects/site: app.log
Only in home/projects/site: node_modules
Always extract into an empty directory first, and copy back what you need. Extracting directly over live data replaces newer files with older ones. Lesson 205 builds a complete, safe restore workflow on top of this script.
Failure Cases
Each check produces a clear message and a specific exit status:
$ ./backup.sh home/projects; echo "status $?"
2026-12-02 17:06:35 ERROR: the destination -d DEST is required (try -h)
status 2
$ ./backup.sh -d b missing; echo "status $?"
2026-12-02 17:06:35 ERROR: source not found: missing
status 2
$ ./backup.sh -d b -k three home/projects; echo "status $?"
2026-12-02 17:06:35 ERROR: KEEP must be a whole number, got 'three'
status 2
$ ./backup.sh -d b -n 'my backup' home/projects; echo "status $?"
2026-12-02 17:06:35 ERROR: NAME may only contain letters, digits, '.', '_' and '-'
status 2
$ ./backup.sh -d b -k; echo "status $?"
2026-12-02 17:06:35 ERROR: option -k needs a value (try -h)
status 2
$ ./backup.sh -d b /; echo "status $?"
2026-12-02 17:06:35 ERROR: refusing to back up the whole file system
status 2
The -k case comes from getopts: with a leading : in the option string, a missing value sets opt to : and OPTARG to the option letter (lesson 130).
An exclude file containing * is caught by the entry count, and no archive is left behind:
$ printf '*\n' > all.txt
$ ./backup.sh -d b3 -x all.txt home/projects; echo "status $?"
2026-12-02 17:06:35 starting backup 'projects' of: home/projects
2026-12-02 17:06:35 ERROR: archive is empty (check the exclude patterns)
status 1
$ ls -A b3
.backup.lock backup.log
Overlapping Runs
To simulate a long-running backup, hold the lock in the current shell and start the script:
$ exec 8> backups/.backup.lock; flock 8
$ ./backup.sh -d backups home/projects; echo "status $?"
2026-12-02 17:06:35 ERROR: another backup is already writing to /home/suriya/lab/backups
status 3
$ exec 8>&-
The message shows the absolute path of the destination (here the test folder was /home/suriya/lab). exec 8>&- closes the descriptor and releases the lock.
Interrupting a Backup
The following test backs up 300 MB of random data (which does not compress) and sends SIGINT to the script after one and a half seconds:
$ mkdir big && head -c 300M /dev/urandom > big/blob.bin
$ ./backup.sh -d b4 big & sleep 1.5; kill -INT $!; wait $!; echo "status $?"
2026-12-02 17:06:36 starting backup 'big' of: big
2026-12-02 17:06:44 ERROR: interrupted
status 1
$ ls -A b4
.backup.lock backup.log
No .partial file and no half-finished archive remain. Notice the time stamps: the interruption was logged eight seconds later, when tar had finished. kill -INT $! sends the signal only to the Bash process, and Bash runs a trap only after the foreground command it is waiting for has ended. Pressing Ctrl+C in a terminal behaves differently: the terminal sends SIGINT to the whole foreground process group, so tar is stopped at once and the trap runs immediately. Either way, the cleanup is the same.
Scheduling the Backup
A crontab entry (lesson 170) that backs up a projects folder every night at 02:15 and keeps two weeks of history:
15 2 * * * /usr/local/bin/backup.sh -d /srv/backups -x /etc/backup/excludes.txt -k 14 /home/suriya/projects >/dev/null 2>&1
Everything the script does is already recorded in /srv/backups/backup.log, so the cron output can be discarded. To be warned about failures, wrap the call so a non-zero exit status sends a notification (lesson 173), for example backup.sh ... || notify "backup failed with status $?".
A backup stored on the same disk as the original protects against deleted files and mistakes, but not against a failed disk or a stolen laptop. For real protection, copy the archives and their .sha256 files to another machine or to object storage (for example with scp or rclone), and run sha256sum -c on the copies.
Ideas for Extending the Project
- Other compressors. Accept
-z gzip|xz|zstdand set the tar option (--gzip,--xz,--zstd) and file extension accordingly.xzgives smaller archives at the cost of CPU time;zstdis much faster. - A minimum free-space check. Before starting, compare
df --output=avail -B1 "$dest"withdu -sbof the sources and refuse to start if the backup clearly cannot fit. - Time-based retention. Instead of keeping a fixed number, delete backups older than D days with
find "$dest" -name "$name-*.tar.gz" -mtime +D, while always keeping at least the newest one. - Incremental backups. GNU
tar --listed-incremental=SNAPSHOT_FILEstores only files changed since the last run. A weekly full backup plus daily incremental ones saves a lot of space. - Encryption. Pipe the archive through
gpg --symmetricoragebefore writing it, for backups that leave the machine.