Build a Safe Automated Backup and Restore Workflow
A backup is only useful if it can be restored. Many backup scripts do half of the job: they create an archive every night, and nobody notices for months that the archives are empty, damaged or incomplete. And when the day of the restore comes, a careless tar -x can overwrite the files that survived. This final project builds safebackup.sh, a script that treats backup, verification and restore as one workflow: every backup is checked immediately, every restore is checked again before anything is written, and a restore never overwrites existing data.
Lesson 164 introduced backups with Bash, lesson 194 built a time-stamped backup script, and lesson 200 backed up a database. This project adds the parts that make a backup trustworthy: checksums, read-back tests, protection against unsafe archives and a restore that refuses to destroy data.
What the Script Should Do
- Back up a directory into a compressed
tararchive with a time stamp in its name. - Record a checksum (SHA-256) next to every archive, and check it right after the backup.
- List the archives and verify any archive at any time.
- Restore an archive (the newest one by default) into a directory that is new or empty, after checking its checksum and its contents.
- Keep only the newest few archives.
- Refuse to run twice at the same time, and offer a dry run for the restore.
Design Decisions
Never Publish a Half-Written Archive
The archive is first written under the name NAME.tar.gz.partial and renamed only when tar has finished and the file can be read back:
tar -czf "$tmp" -C "$abs/.." -- "$base"
tar -tzf "$tmp" > /dev/null || fail "the new archive cannot be read back"
mv -- "$tmp" "$backupdir/$name"
tar -czf creates a gzip-compressed archive. The option -C "$abs/.." changes into the parent directory first, and the last argument is only the directory name. This stores relative paths such as data/docs/report.txt and not /home/user/data/docs/report.txt, which makes the archive easy to restore anywhere. The second command, tar -tzf, only lists the contents, but to list them tar has to decompress the whole file, so it finds a damaged archive. Because the final name appears with a rename, which is atomic within one file system, a crash can never leave a file that looks like a good backup but is not.
A trap removes the partial file if the script stops early. The variable tmp is global on purpose: an EXIT trap runs when the script ends, after a function has returned, and a local variable would no longer exist. Under set -u, the trap would then fail with "unbound variable" and turn a successful backup into exit status 1. This is a real mistake that was found while testing this script.
Checksums Detect Silent Damage
Disks, networks and copy tools sometimes change a byte without any error. A checksum is a short fingerprint of the file's contents: if even one bit changes, the fingerprint is completely different. The script saves one next to each archive:
( cd "$backupdir" && sha256sum -- "$name" > "$name.sha256" )
The command runs in a subshell, after cd, so the checksum file contains only the file name and no path. This is what lets you move the whole backup directory elsewhere and still verify it with sha256sum -c. The check uses the exit status only:
( cd "$backupdir" && sha256sum --status -c "${archive##*/}.sha256" ) ||
fail "CHECKSUM MISMATCH: ${archive##*/} is damaged"
--status prints nothing and reports the result through the exit status, and the || handles the failure with a clear message. The function check_archive combines this with the readability test of tar, and it is called three times during the life of an archive: right after the backup, when you run verify, and at the start of every restore.
Keeping the Newest Archives
The names contain the date and time (backup-YYYYMMDD-HHMMSS-NAME.tar.gz), so alphabetical order is chronological order. After a successful backup the script removes the oldest archives, together with their .sha256 files, until only KEEP remain. The pruning runs only after the new backup has been verified, so a failing backup can never cost you the older ones.
Choosing the Archive
pick_archive returns the full path of a named archive, or the newest one when no name is given:
name=$(archives | tail -n 1)
It strips any directory from a name given by the user (${name##*/}), so ../../etc/passwd can only ever mean a file inside the backup directory.
A Restore That Cannot Destroy Data
A restore is the most dangerous moment of a backup system, because people do it in a hurry and often on a system that is already damaged. The script protects the user in four steps:
Verify first. The checksum and the readability test run before anything is written.
Inspect the archive. An archive can contain a path that starts with
/or contains.., which would write outside the destination. The script reads the list of members and stops at the first unsafe name:case $entry in /*|..|../*|*/..|*/../*) fail "unsafe path in archive: $entry" ;; esacRefuse an occupied destination. If the destination exists, it must be an empty directory. A restore into a new directory also lets you compare the result with the live data before you copy anything back.
Do not copy ownership.
--no-same-ownermakes the restored files belong to the user who runs the command, so a restore by an administrator cannot recreate files owned by a user ID that means something different on this machine.
Reading Names Safely
The test data deliberately contains a file with a space in its name (my files/notes 1.txt) and a file whose name starts with a dash (-dash.txt). The script quotes every variable, uses -- before names and uses IFS= read -r for lists (lessons 111 and 161), so both are archived and restored correctly.
The Complete Script
#!/usr/bin/env bash
#
# safebackup.sh - back up a directory, verify the backup, and restore it safely
#
# Usage: safebackup.sh [-d BACKUPDIR] [-k KEEP] backup SOURCE_DIR
# safebackup.sh [-d BACKUPDIR] list
# safebackup.sh [-d BACKUPDIR] verify [ARCHIVE]
# safebackup.sh [-d BACKUPDIR] [-n] restore [ARCHIVE] DESTINATION
#
# Commands:
# backup SOURCE_DIR create a compressed archive plus a checksum file
# list show the archives, newest last
# verify [ARCHIVE] check the checksum and that tar can read the archive
# restore [ARCHIVE] DEST unpack into DEST, which must be new or empty
#
# Options:
# -d BACKUPDIR where archives are kept (default: ./backups)
# -k KEEP archives to keep after a backup (default: 5)
# -n dry run for restore: only list what would be restored
# -h show this help
#
# Without ARCHIVE, the newest archive is used.
# Exit status: 0 success, 1 a check failed, 2 usage error, 3 another run is active.
set -euo pipefail
export LC_ALL=C
readonly PROG=${0##*/}
usage() { sed -n '3,26s/^# \{0,1\}//p' "$0"; }
die() { printf '%s: %s\n' "$PROG" "$1" >&2; exit 2; }
fail() { printf '%s: %s\n' "$PROG" "$1" >&2; exit 1; }
log() { printf '%s %s\n' "$(date '+%H:%M:%S')" "$*"; }
backupdir=./backups keep=5 dry=0 tmp=
while getopts ':d:k:nh' opt; do
case $opt in
d) backupdir=$OPTARG ;;
k) keep=$OPTARG ;;
n) dry=1 ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
[[ $keep =~ ^[1-9][0-9]*$ ]] || die "-k needs a whole number of at least 1"
(( $# >= 1 )) || die "give a command: backup, list, verify or restore (try -h)"
cmd=$1; shift
# --- helpers --------------------------------------------------------------------
archives() { # archive file names, oldest first (the names contain a timestamp)
local f
for f in "$backupdir"/backup-*.tar.gz; do
[[ -f $f ]] && printf '%s\n' "${f##*/}"
done | sort
}
pick_archive() { # pick_archive [NAME] -> prints the full path of NAME or of the newest archive
local name=${1:-}
if [[ -z $name ]]; then
name=$(archives | tail -n 1)
[[ -n $name ]] || fail "there are no archives in $backupdir"
fi
name=${name##*/}
[[ -f $backupdir/$name ]] || fail "no such archive: $name"
printf '%s\n' "$backupdir/$name"
}
lock() {
mkdir -p "$backupdir"
exec 9> "$backupdir/.lock"
flock -n 9 || { printf '%s: another run is active\n' "$PROG" >&2; exit 3; }
}
check_archive() { # check_archive PATH - checksum and readability
local archive=$1
[[ -f $archive.sha256 ]] || fail "missing checksum file for ${archive##*/}"
( cd "$backupdir" && sha256sum --status -c "${archive##*/}.sha256" ) ||
fail "CHECKSUM MISMATCH: ${archive##*/} is damaged"
tar -tzf "$archive" > /dev/null 2>&1 || fail "tar cannot read ${archive##*/}"
}
# --- commands -------------------------------------------------------------------
do_backup() {
(( $# == 1 )) || die "backup needs SOURCE_DIR"
local source=$1
[[ -d $source ]] || die "source is not a directory: $source"
[[ -r $source ]] || die "cannot read $source"
local abs; abs=$(cd "$source" && pwd -P)
local backupabs; backupabs=$(mkdir -p "$backupdir" && cd "$backupdir" && pwd -P)
[[ $backupabs/ != "$abs"/* ]] || die "the backup directory must not be inside the source"
lock
local base=${abs##*/}
local name="backup-$(date '+%Y%m%d-%H%M%S')-${base//[^A-Za-z0-9._-]/_}.tar.gz"
tmp="$backupdir/$name.partial" # global on purpose: the EXIT trap runs after this function ends
trap 'rm -f -- "${tmp:-}"' EXIT
log "archiving $abs"
tar -czf "$tmp" -C "$abs/.." -- "$base"
tar -tzf "$tmp" > /dev/null || fail "the new archive cannot be read back"
mv -- "$tmp" "$backupdir/$name"
( cd "$backupdir" && sha256sum -- "$name" > "$name.sha256" )
log "created $name ($(du -h -- "$backupdir/$name" | cut -f1), $(tar -tzf "$backupdir/$name" | wc -l) entries)"
check_archive "$backupdir/$name"
log "verified checksum"
local all=() a excess
mapfile -t all < <(archives)
excess=$(( ${#all[@]} - keep ))
for a in "${all[@]}"; do
(( excess > 0 )) || break
log "removing old archive $a"
rm -f -- "${backupdir:?}/${a:?}" "${backupdir:?}/${a:?}.sha256"
excess=$((excess - 1))
done
}
do_list() {
local a count=0
while read -r a; do
[[ -n $a ]] || continue
printf '%-48s %8s\n' "$a" "$(du -h -- "$backupdir/$a" | cut -f1)"
count=$((count + 1))
done < <(archives)
(( count > 0 )) || echo "(no archives in $backupdir)"
}
do_verify() {
local archive; archive=$(pick_archive "${1:-}")
check_archive "$archive"
log "OK: ${archive##*/} matches its checksum and can be read"
}
do_restore() {
local archive dest
case $# in
1) archive=$(pick_archive ""); dest=$1 ;;
2) archive=$(pick_archive "$1"); dest=$2 ;;
*) die "restore needs [ARCHIVE] and DESTINATION" ;;
esac
check_archive "$archive"
# refuse archives that could write outside the destination
local entry
while IFS= read -r entry; do
case $entry in
/*|..|../*|*/..|*/../*) fail "unsafe path in archive: $entry" ;;
esac
done < <(tar -tzf "$archive")
if (( dry )); then
log "[dry run] would restore ${archive##*/} into $dest:"
tar -tzf "$archive" | sed -n '1,10p'
return 0
fi
if [[ -e $dest ]]; then
[[ -d $dest ]] || die "$dest exists and is not a directory"
[[ -z $(ls -A -- "$dest") ]] || fail "$dest is not empty; restore into a new or empty directory"
fi
mkdir -p -- "$dest"
log "restoring ${archive##*/} into $dest"
tar -xzf "$archive" -C "$dest" --no-same-owner
log "restored $(find "$dest" -type f | wc -l) file(s)"
}
case $cmd in
backup) do_backup "$@" ;;
list) do_list ;;
verify) do_verify "$@" ;;
restore) do_restore "$@" ;;
*) die "unknown command '$cmd' (try -h)" ;;
esac
Running the Workflow
The examples use a small directory with three files, one of them with a space in its name and one starting with a dash. The long path that the script prints in the first line is shortened here:
$ find data -type f
data/-dash.txt
data/docs/report.txt
data/my files/notes 1.txt
Making and Checking a Backup
$ ./safebackup.sh -d store -k 3 backup data
20:39:13 archiving /home/user/data
20:39:13 created backup-20261202-203913-data.tar.gz (4.0K, 6 entries)
20:39:13 verified checksum
The six entries are three files and three directories. The last line proves that the archive already matched its checksum when the script finished. Three more backups (after changes to report.txt) show the pruning with -k 3:
20:39:16 created backup-20261202-203916-data.tar.gz (4.0K, 6 entries)
20:39:16 verified checksum
20:39:16 removing old archive backup-20261202-203913-data.tar.gz
$ ./safebackup.sh -d store list
backup-20261202-203914-data.tar.gz 4.0K
backup-20261202-203915-data.tar.gz 4.0K
backup-20261202-203916-data.tar.gz 4.0K
Verifying at Any Time
$ ./safebackup.sh -d store verify
20:39:16 OK: backup-20261202-203916-data.tar.gz matches its checksum and can be read
Run verify from cron every week. A backup that is never checked is a hope, not a backup.
A Dry Run of the Restore
$ ./safebackup.sh -d store -n restore out
20:39:00 [dry run] would restore backup-20261202-203859-data.tar.gz into out:
data/
data/my files/
data/my files/notes 1.txt
data/-dash.txt
data/docs/
data/docs/report.txt
The dry run still verifies the archive, but it writes nothing: the directory out does not exist afterwards.
Restoring and Comparing
$ ./safebackup.sh -d store restore out
20:39:16 restoring backup-20261202-203916-data.tar.gz into out
20:39:16 restored 3 file(s)
$ diff -r data out/data && echo identical
identical
diff -r compares two directory trees file by file, and it printed nothing because they are the same. Restoring an older archive is done by naming it; report.txt then has the older content:
$ ./safebackup.sh -d store restore backup-20261202-203914-data.tar.gz out_old
$ cat out_old/data/docs/report.txt
v2
The Safety Checks in Action
A second restore into the same directory is refused, and nothing is overwritten:
$ ./safebackup.sh -d store restore out
safebackup.sh: out is not empty; restore into a new or empty directory
An archive whose member names climb out of the destination (created by hand for this test, with a correct checksum) is refused too, and the destination is not even created:
$ ./safebackup.sh -d store restore out3
safebackup.sh: unsafe path in archive: ../f
Damage is found by the checksum. After one byte in the newest archive was changed on purpose:
$ ./safebackup.sh -d store verify
safebackup.sh: CHECKSUM MISMATCH: backup-20261202-203916-data.tar.gz is damaged
$ echo $?
1
The restore command stops with the same message before it writes a single file. Overlapping runs are also refused (the lock from lesson 171):
$ ./safebackup.sh -d store backup data
safebackup.sh: another run is active
$ echo $?
3
Input Errors
These exit with status 2 (a usage error) unless noted:
$ ./safebackup.sh
safebackup.sh: give a command: backup, list, verify or restore (try -h)
$ ./safebackup.sh backup nodir
safebackup.sh: source is not a directory: nodir
$ ./safebackup.sh -d data/b backup data
safebackup.sh: the backup directory must not be inside the source
$ ./safebackup.sh -k 0 list
safebackup.sh: -k needs a whole number of at least 1
$ ./safebackup.sh -d empty_store restore x (status 1)
safebackup.sh: there are no archives in empty_store
The check that the backup directory is not inside the source prevents a classic mistake: every backup would contain all earlier backups and grow without limit.
Scheduling and Keeping Copies Elsewhere
Run the backup every night with cron (lesson 170), and verify once a week:
15 2 * * * /usr/local/bin/safebackup.sh -d /srv/backups -k 14 backup /srv/app/data
40 3 * * 0 /usr/local/bin/safebackup.sh -d /srv/backups verify
Both lines were not executed as shown. A backup in the same place as the original does not help against a failing disk, a deleted server or ransomware. Copy the archives and their .sha256 files to another machine, for example with scp or rsync (lesson 179), and verify them there with the same script, because the checksum file travels with the archive.
Ideas for Extending the Project
- Encryption. Pipe the archive through
gpg --symmetricoragebefore it leaves the machine, and keep the key somewhere else (lesson 158). - Exclude patterns. Add
-x PATTERNoptions that are passed totar --exclude. - Partial restore. Allow
restore ARCHIVE DEST PATH...to extract only some files withtar -xzf archive path. - Restore test. Add a command
drillthat restores the newest archive into a temporary directory, compares it with the source and removes it. This is the most honest test of a backup. - Notifications. Call the script from lesson 173 when a backup or a verification fails.