Build a Safe Automated Backup and Restore Workflow

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 205 of 205

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

  1. Back up a directory into a compressed tar archive with a time stamp in its name.
  2. Record a checksum (SHA-256) next to every archive, and check it right after the backup.
  3. List the archives and verify any archive at any time.
  4. Restore an archive (the newest one by default) into a directory that is new or empty, after checking its checksum and its contents.
  5. Keep only the newest few archives.
  6. 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:

  1. Verify first. The checksum and the readability test run before anything is written.

  2. 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" ;;
    esac
  3. Refuse 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.

  4. Do not copy ownership. --no-same-owner makes 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 --symmetric or age before it leaves the machine, and keep the key somewhere else (lesson 158).
  • Exclude patterns. Add -x PATTERN options that are passed to tar --exclude.
  • Partial restore. Allow restore ARCHIVE DEST PATH... to extract only some files with tar -xzf archive path.
  • Restore test. Add a command drill that 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Build a Safe Automated Backup and Restore Workflow and get answers drawn from it.

Signed-in readers only.