Automating Backups with Bash
A backup is a copy of data, kept somewhere else, that you can use to get the data back after it is deleted, corrupted, encrypted by ransomware or lost with a failed disk. Backups only protect you if they actually happen, on time, every time, so they are one of the most common things people automate with Bash. A backup script combines many skills from this tutorial: building commands from variables, checking exit statuses, handling file names safely, working with dates, logging and cleaning up after failures.
This lesson explains what a good backup must guarantee, how the standard Linux tools (tar, compression programs, sha256sum) create and verify backup archives, how incremental backups and retention work, and then builds a complete backup script that can run unattended from a scheduler.
Understanding the Concept
A backup is only useful if you can restore from it. That simple test leads to a list of requirements:
| Requirement | Why it matters |
|---|---|
| Complete | it includes everything needed to rebuild the data, and nothing important is silently skipped |
| Consistent | files are not captured halfway through being written |
| Verified | the archive is known to be readable and undamaged |
| Separate | it is stored on a different disk, and ideally a different machine or site, from the original |
| Retained | several older versions are kept, so a problem noticed late can still be undone |
| Private | its permissions protect the data as well as the original's do |
| Automatic | it runs without anyone remembering to start it, and failures are reported |
| Tested | someone has actually restored from it |
A widely used rule of thumb is 3-2-1: keep three copies of important data, on two different types of storage, with one copy off-site. A Bash script usually handles the first steps: creating the archive locally and verifying it. Copying it to another machine or to cloud storage is then a second, separate step.
Choosing What to Back Up
Back up the data that cannot be recreated, and leave out what can:
- Include: user files and uploads, configuration (
/etc, application config files), application data, database dumps, scripts and crontabs. - Exclude: caches, temporary files, build output, log files you do not need, package folders such as
node_modulesthat can be reinstalled, and the backup folder itself.
Databases need special care. Copying the files of a running database server can capture them in an inconsistent state. Instead, use the database's own dump tool (for example mysqldump or pg_dump) to write a consistent export to a file, and back up that file.
Creating an Archive with tar
tar (tape archive) packs a folder tree, including file names, permissions, owners and timestamps, into a single file. The -z option compresses it with gzip. The site folder used in this lesson contains html/index.html, uploads/my photo.jpg, app.conf and a cache folder:
ts=$(date +%Y%m%d-%H%M%S)
tar -czf "backups/site-$ts.tar.gz" -C /srv/t164 --exclude='site/cache' site
tar -tzf "backups/site-$ts.tar.gz"
site/
site/html/
site/html/index.html
site/uploads/
site/uploads/my photo.jpg
site/app.conf
The options in detail:
-ccreates an archive,-zcompresses it with gzip, and-f FILEnames the archive file.-tlists the contents instead of creating.-C /srv/t164changes into that folder before adding files, so the archive stores the relative pathsite/.... Archives with relative paths can be restored anywhere.--exclude=PATTERNskips matching paths. Put--excludeoptions before the names of the files to archive, because GNU tar applies them only to names that follow.- The timestamp in the file name (
site-20261124-105943.tar.gz) makes every archive name unique and lets names sort in date order. The format%Y%m%d-%H%M%Ssorts correctly as plain text.
If you give tar an absolute path instead, it removes the leading slash and warns you:
tar -czf backups/abs.tar.gz /srv/t164/site/app.conf
tar -tzf backups/abs.tar.gz
tar: Removing leading `/' from member names
srv/t164/site/app.conf
This protects you during a restore, because extracting the archive cannot overwrite files in / by accident. Using -C is cleaner and avoids the warning.
Compression choices
| Option | Program | Typical use |
|---|---|---|
-z | gzip | fast, available everywhere; the safe default |
-J | xz | much smaller archives, but much slower to create |
--zstd | zstd | close to xz in size and faster than gzip, if zstd is installed |
| (none) | no compression | data that is already compressed, such as photos and videos |
The file name extension should match: .tar.gz, .tar.xz, .tar.zst or .tar.
tar's exit status
GNU tar uses three exit statuses, and a backup script must handle them differently:
| Status | Meaning |
|---|---|
| 0 | success |
| 1 | some files changed while tar was reading them; the archive is complete, but those files may be inconsistent |
| 2 | a fatal error, such as an unreadable file or a full disk; the archive cannot be trusted |
Treating status 1 as a warning and status 2 as a failure is the usual approach.
Verifying a Backup
An archive that cannot be read is worse than no archive, because it gives false confidence. Three checks, from quickest to most thorough:
gzip -t "backups/site-$ts.tar.gz" && echo "gzip ok"
(cd backups && sha256sum "site-$ts.tar.gz" > "site-$ts.tar.gz.sha256" && sha256sum -c "site-$ts.tar.gz.sha256")
gzip ok
site-20261124-105943.tar.gz: OK
gzip -ttests the compressed data without extracting anything.tar -tzf ARCHIVE > /dev/nullreads the whole archive and checks its structure.- A checksum file made with
sha256sumrecords a fingerprint of the archive. Later, for example after copying it to another server,sha256sum -cproves that the copy is identical. The.sha256file stores the file name without a folder, which is why the commands run insidebackupswithcd.
To see what these checks catch, four bytes in the middle of a copy of an archive were overwritten with zeros:
sha256sum -c bad.sha256; echo "sha status $?"
gzip -t bad.tar.gz; echo "gzip -t status $?"
tar -tzf bad.tar.gz >/dev/null; echo "tar -t status $?"
bad.tar.gz: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
sha status 1
gzip: bad.tar.gz: invalid compressed data--format violated
gzip -t status 1
gzip: stdin: invalid compressed data--format violated
tar: Child returned status 1
tar: Error is not recoverable: exiting now
tar -t status 2
All three detected the damage. The final and best test is a real restore: extract the archive into an empty folder and compare it with the original, for example with diff -r. Do this regularly, not only when you need the data.
Full and Incremental Backups
A full backup copies everything each time. It is simple and each archive restores on its own, but it takes the most time and space. An incremental backup copies only what changed since the previous backup.
GNU tar supports incremental backups with --listed-incremental=SNAPSHOT_FILE. The snapshot file records the state of every file, and the next run uses it to decide what changed:
tar -czf inc/level0.tar.gz --listed-incremental=inc/site.snar -C /srv/t164 site
echo "full: $(tar -tzf inc/level0.tar.gz | wc -l) entries"
echo 'new post' > site/html/post.html; echo '<h1>Home v2</h1>' > site/html/index.html
tar -czf inc/level1.tar.gz --listed-incremental=inc/site.snar -C /srv/t164 site
tar -tzf inc/level1.tar.gz
full: 8 entries
site/
site/cache/
site/html/
site/uploads/
site/html/index.html
site/html/post.html
The first run, with no snapshot file yet, made a full (level 0) backup. The second archive contains only the two changed files, plus the folder entries tar needs to record the structure. To restore, extract the full archive and then every incremental archive in order, with --listed-incremental=/dev/null so tar also applies deletions recorded in the increments:
mkdir -p restore
tar -xzf inc/level0.tar.gz -C restore --listed-incremental=/dev/null
tar -xzf inc/level1.tar.gz -C restore --listed-incremental=/dev/null
diff -r site restore/site && echo "restore matches source"
restore matches source
Every incremental archive depends on all the archives before it, so losing one breaks the chain. A common schedule makes a full backup weekly and incremental backups daily, and keeps each week's chain together.
Mirrors with rsync
rsync is the other standard backup tool. Instead of creating archive files, it makes a destination folder match a source folder, copying only the differences, also across SSH to another machine. rsync --archive --delete SRC/ DEST/ keeps an exact mirror. A mirror alone is not a full backup: if a file is deleted or damaged at the source, the next run copies that change to the mirror too. The --link-dest option solves this by creating a new dated folder for each run, where unchanged files are hard links to the previous run's copies, so every snapshot looks complete while only changed files take new space.
Retention: Keeping the Right Number of Backups
Without cleanup, backups eventually fill the disk, and then the newest backup fails. Retention removes archives beyond a limit, either by count ("keep the 7 newest") or by age ("delete anything older than 30 days", lesson 165). Retention code deletes files, so it needs the same care as any destructive command (lesson 160):
- Match only this job's archives, with an exact pattern. A loose pattern like
site-*would also match the archives of another job namedsite-old. - Delete only after the new backup has been created and verified, so a failing job never removes the last good copy.
- Never let an empty variable turn the pattern into something like
/*.tar.gz.
Making Backups Safe to Automate
A script that runs every night from a scheduler such as cron (lesson 170) has no one watching it, so it must protect itself:
- Write to a temporary name, then rename. If the job is interrupted, a half-written
.partialfile is never mistaken for a finished backup.mvwithin one file system is atomic: the archive appears under its final name all at once. - Clean up on failure with an EXIT trap (lesson 124).
- Check free space before starting.
- Use a restrictive umask.
umask 077makes new archives readable only by their owner; a backup of private data must not be readable by everyone. - Refuse dangerous combinations, such as a destination inside the source folder, which would make each backup contain the previous ones.
- Log with timestamps to standard output and errors to standard error, so cron or a log file captures what happened.
- Prevent overlapping runs with a lock (lesson 171) when a job could run longer than its interval.
- Exit with a meaningful status, so a monitoring system or a notification step (lesson 173) can report failures.
A Complete Example: A Backup Script
backup.sh creates a timestamped, compressed, verified archive of one folder, writes a checksum file next to it and keeps a configurable number of archives. It supports a dry run.
#!/usr/bin/env bash
#
# backup.sh - create a timestamped, verified .tar.gz backup and prune old ones
#
# Usage: backup.sh [-n] [-k KEEP] NAME SOURCE_DIR DEST_DIR
# -n dry run: report what would happen, change nothing
# -k KEEP number of NAME archives to keep in DEST_DIR (default: 7)
#
# Creates DEST_DIR/NAME-YYYYmmdd-HHMMSS.tar.gz and a matching .sha256 file.
# Exit status: 0 success, 1 failure, 2 bad usage.
set -euo pipefail
umask 077 # archives may contain private data
readonly DEFAULT_KEEP=7
readonly EXCLUDES=( # never worth backing up
--exclude='*.tmp'
--exclude='cache'
--exclude='.git'
)
dry_run=0
keep=$DEFAULT_KEEP
partial='' # archive being written; removed on failure
trap '[[ -n $partial ]] && rm -f -- "$partial"' EXIT
log() { printf '%s %s\n' "$(date '+%F %T')" "$*"; }
die() { log "ERROR: $*" >&2; exit 1; }
usage() { echo "usage: ${0##*/} [-n] [-k KEEP] NAME SOURCE_DIR DEST_DIR" >&2; exit 2; }
parse_args() {
local opt
while getopts ':nk:' opt; do
case $opt in
n) dry_run=1 ;;
k) keep=$OPTARG ;;
*) usage ;;
esac
done
shift $((OPTIND - 1))
(( $# == 3 )) || usage
name=$1 src=$2 dest=$3
[[ $name =~ ^[A-Za-z0-9_-]+$ ]] || die "invalid NAME: ${name@Q}"
[[ $keep =~ ^[0-9]+$ ]] && (( 10#$keep >= 1 )) || die "KEEP must be 1 or more: ${keep@Q}"
keep=$((10#$keep))
}
check_paths() {
local real
real=$(realpath -e -- "$src" 2>/dev/null) || die "source not found: $src"
src=$real
[[ -d $src ]] || die "source is not a folder: $src"
[[ $src != / ]] || die 'refusing to back up /'
dest=$(realpath -m -- "$dest")
[[ $dest/ != "$src"/* ]] || die "DEST_DIR must not be inside SOURCE_DIR: $dest"
(( dry_run )) || mkdir -p -- "$dest"
}
check_space() {
local needed avail probe=$dest
needed=$(du -sb -- "$src" | cut -f1) # uncompressed size: a safe upper bound
while [[ ! -d $probe ]]; do probe=$(dirname -- "$probe"); done # dry run: DEST may not exist yet
avail=$(df --output=avail -B1 -- "$probe" | tail -n 1)
log "source $src: $needed bytes; free at destination: $avail bytes"
(( avail > needed )) || die "not enough free space in $dest"
}
create_archive() {
local stamp archive rc=0 entries
stamp=$(date +%Y%m%d-%H%M%S)
archive=$dest/$name-$stamp.tar.gz
[[ ! -e $archive ]] || die "archive already exists (two runs in one second?): $archive"
if (( dry_run )); then
log "dry run: would create $archive"
return
fi
partial=$archive.partial
tar -czf "$partial" -C "$(dirname -- "$src")" "${EXCLUDES[@]}" -- "$(basename -- "$src")" || rc=$?
case $rc in
0) ;;
1) log 'WARNING: some files changed while they were being read' ;;
*) die "tar failed with status $rc" ;;
esac
entries=$(tar -tzf "$partial" | wc -l) || die "archive failed verification: $partial"
mv -- "$partial" "$archive"
partial=''
( cd -- "$dest" && sha256sum -- "${archive##*/}" > "${archive##*/}.sha256" )
log "created $archive ($entries entries, $(stat -c %s -- "$archive") bytes)"
}
prune_old() {
local -a archives=()
local f old
shopt -s nullglob
for f in "$dest/$name"-*.tar.gz; do # glob results are sorted, so oldest first
# exact match only: NAME "site" must not match archives of NAME "site-2025"
[[ ${f##*/} =~ ^$name-[0-9]{8}-[0-9]{6}\.tar\.gz$ ]] && archives+=("$f")
done
shopt -u nullglob
(( ${#archives[@]} > keep )) || { log "keeping all ${#archives[@]} archive(s) of $name"; return; }
for old in "${archives[@]:0:${#archives[@]} - keep}"; do
if (( dry_run )); then
log "dry run: would remove $old"
else
rm -f -- "$old" "$old.sha256"
log "removed $old"
fi
done
}
main() {
parse_args "$@"
check_paths
check_space
create_archive
prune_old
}
main "$@"
How It Works
- Arguments.
NAMElabels the backup job and becomes part of every archive name, so it is restricted to letters, digits,_and-; that also makes it safe to use inside the retention regular expression.KEEPmust be a whole number of at least 1;10#reads it as decimal even with leading zeros. - Paths. The source is resolved with
realpath -eand must be an existing folder other than/. The destination is resolved withrealpath -m, because it may not exist yet, and must not be inside the source. Only after both checks pass is the destination created; a dry run never creates it. - Free space.
du -sbmeasures the source in bytes, which is more than the compressed archive will need, anddf --output=avail -B1reports the free bytes at the destination. In a dry run the destination may not exist, so the loop walks up to the nearest existing parent folder. - Creating the archive. tar writes to
NAME-STAMP.tar.gz.partialwith the archive paths relative to the source's parent folder.|| rc=$?captures tar's status without triggeringset -e, and thecasetreats status 1 as a warning and anything higher as a failure. If the script stops for any reason, the EXIT trap removes the partial file. - Verifying.
tar -tzfreads the whole archive; withpipefail, a failure there fails the command substitution and stops the script before the archive is accepted. Only then is the file renamed to its final name and its checksum written. - Retention. The loop collects only file names that match exactly
NAME-+ 8 digits +-+ 6 digits +.tar.gz. Glob results are sorted, and the timestamp format sorts by date, so the oldest archives come first. Everything except the newestKEEPis removed with its checksum file, and only after the new archive exists.
Bugs Found While Testing
Three problems in the first version of this script were found by testing the error cases, and the fixes are part of the script above:
- The first
check_pathswrote the result ofrealpathstraight intosrc. When the source did not exist, the failed command substitution setsrcto an empty string beforedieused it, so the message readsource not found:with no name. Writing the result to a separate variablerealkeeps the original text for the message. - The first version created the destination folder before checking whether it was inside the source, so a refused run still left an empty
backupsfolder inside the site. The check now comes first. - The first retention pattern,
"$dest/$name"-[0-9]*-[0-9]*.tar.gz, also matched the archives of a job namedsite-2025when pruning the jobsite, because[0-9]*matches any text that begins with a digit. The exact regular expression fixed it; in a test with both jobs writing to one folder, pruningsitedown to one archive left bothsite-2025archives untouched.
Running the Complete Example
A dry run reports what would happen without creating the destination:
backup.sh -n site site /srv/vault; echo "status $?"
2026-11-24 11:01:20 source /srv/t164/site: 48 bytes; free at destination: 32212647936 bytes
2026-11-24 11:01:20 dry run: would create /srv/vault/site-20261124-110120.tar.gz
2026-11-24 11:01:20 keeping all 0 archive(s) of site
status 0
Three real runs, one second apart, keeping two archives:
backup.sh -k 2 site site /srv/vault; echo "status $?" # run three times
ls -l /srv/vault
(cd /srv/vault && sha256sum -c ./*.sha256)
2026-11-24 11:01:20 source /srv/t164/site: 48 bytes; free at destination: 32212643840 bytes
2026-11-24 11:01:20 created /srv/vault/site-20261124-110120.tar.gz (7 entries, 299 bytes)
2026-11-24 11:01:20 keeping all 1 archive(s) of site
status 0
2026-11-24 11:01:21 source /srv/t164/site: 48 bytes; free at destination: 32212635648 bytes
2026-11-24 11:01:21 created /srv/vault/site-20261124-110121.tar.gz (7 entries, 299 bytes)
2026-11-24 11:01:21 keeping all 2 archive(s) of site
status 0
2026-11-24 11:01:22 source /srv/t164/site: 48 bytes; free at destination: 32212627456 bytes
2026-11-24 11:01:22 created /srv/vault/site-20261124-110122.tar.gz (7 entries, 299 bytes)
2026-11-24 11:01:22 removed /srv/vault/site-20261124-110120.tar.gz
status 0
total 16
-rw------- 1 root root 299 Nov 24 11:01 site-20261124-110121.tar.gz
-rw------- 1 root root 94 Nov 24 11:01 site-20261124-110121.tar.gz.sha256
-rw------- 1 root root 299 Nov 24 11:01 site-20261124-110122.tar.gz
-rw------- 1 root root 94 Nov 24 11:01 site-20261124-110122.tar.gz.sha256
site-20261124-110121.tar.gz: OK
site-20261124-110122.tar.gz: OK
The third run removed the oldest archive, both remaining archives pass their checksum test, and umask 077 made every file readable only by its owner (-rw-------). Each archive has 7 entries because the cache folder and the .git folder in the site were excluded.
Restoring the newest archive into an empty folder and comparing it with the source shows that the backup is usable:
mkdir -p restore-test
tar -xzf /srv/vault/site-20261124-110122.tar.gz -C restore-test
diff -r --exclude=cache --exclude=.git site restore-test/site && echo "restore matches source (except excluded folders)"
restore matches source (except excluded folders)
Invalid input and dangerous combinations are refused (timestamps shortened to TIME):
$ backup.sh site site site/backups
TIME ERROR: DEST_DIR must not be inside SOURCE_DIR: /srv/t164/site/backups
status 1
$ backup.sh site missing vault
TIME ERROR: source not found: missing
status 1
$ backup.sh my.site site vault
TIME ERROR: invalid NAME: 'my.site'
status 1
$ backup.sh -k 0 site site vault
TIME ERROR: KEEP must be 1 or more: '0'
status 1
$ backup.sh site / vault
TIME ERROR: refusing to back up /
status 1
$ backup.sh site site
usage: backup.sh [-n] [-k KEEP] NAME SOURCE_DIR DEST_DIR
status 2
Finally, a failure in the middle of the backup leaves nothing behind. Run as the unprivileged user nobody, with one file in the source made unreadable, tar fails with status 2:
TIME source /srv/t164/np/site: 48 bytes; free at destination: 32212783104 bytes
tar: site/app.conf: Cannot open: Permission denied
tar: Exiting with failure status due to previous errors
TIME ERROR: tar failed with status 2
The script exited with status 1 and the destination folder was empty afterwards: the EXIT trap removed the .partial file, so no incomplete archive could be mistaken for a good one. To run this script every night, schedule it with cron (lesson 170), for example 30 2 * * * /usr/local/bin/backup.sh site /srv/www/site /srv/backups >> /var/log/backup-site.log 2>&1, and copy the finished archives and their .sha256 files to a second location.