Build a Database Backup Automation Script
This project builds dbbackup.sh, a script that backs up one database (MySQL or MariaDB, PostgreSQL, or SQLite) into a compressed dump file, checks that the dump is complete, stores a checksum next to it, and deletes old backups so the disk does not fill up. It keeps passwords off the command line, refuses to run twice at the same time, writes a log, and reports success or failure through its exit status, so it can run from cron without anyone watching.
Lesson 164 showed how to back up files with Bash. A database needs more care. A copy of the raw database files taken while the server is writing can be corrupt, so the script uses each database's own dump tool, which produces a consistent snapshot as a text file of SQL statements. The main rule of this project is: a backup that has not been verified is only a hope.
What the Script Should Do
- Dump a database with the right tool for its type:
mysqldump,pg_dumporsqlite3 .dump. - Compress the dump on the fly with
gzip, without writing a large uncompressed file first. - Protect credentials: no password in the command line or in the process list.
- Verify the result: the compressed file is intact and the dump ends with the line that only a complete dump has.
- Publish safely: the file gets its final name only after verification, and a
.sha256checksum is stored with it. - Rotate: keep only the newest
-kbackups of each database. - Prevent overlap: a second run while one is active exits with status 3.
- Log every run, and print errors even in quiet mode.
Design Decisions
Why Use the Dump Tools
| Type | Command | Why it is safe to run on a live database |
|---|---|---|
| MySQL, MariaDB | mysqldump --single-transaction | Reads all InnoDB tables inside one transaction, so the dump is a consistent snapshot while the application keeps writing |
| PostgreSQL | pg_dump | Always runs inside one snapshot transaction |
| SQLite | sqlite3 FILE .dump | Reads the database through SQLite, which handles locking correctly |
All three print plain SQL (CREATE TABLE ..., INSERT ...) that can be restored with the matching client tool. The script adds --routines --triggers for MySQL so that stored procedures and triggers are included, and --no-owner for PostgreSQL so the dump can be restored under a different user.
Keeping Passwords Out of the Command Line
Any user on the machine can see the arguments of all running programs with ps. A command like mysqldump -pSECRET shop therefore publishes the password for as long as it runs. The script never does this:
MySQL: the login lives in an option file that is passed with
--defaults-extra-file:[client] user=backup password=secretCreate it with
chmod 600so that only its owner can read it. The script refuses to use the file when group or other users have any permission on it:perms=$(stat -c '%a' "$cnf") (( (8#$perms & 8#077) == 0 )) || die "$cnf must not be readable by other users (chmod 600 $cnf)"stat -c '%a'prints the permissions in octal, for example600. Prefixing8#makes Bash read the number as octal, and the bit mask8#077selects the group and other bits. The test succeeds only when all of them are zero.PostgreSQL:
pg_dumpreads~/.pgpass(or the file inPGPASSFILE) by itself, with lines in the formathost:port:database:user:password.SQLite has no passwords; access is controlled by file permissions.
The script also runs umask 077, so every file it creates (backup, checksum, log) is readable only by its owner. A database dump contains all the data of the application, and it deserves the same protection as the database.
Compressing in a Pipeline
if ! "${dump_cmd[@]}" 2> "$part.err" | gzip -9 > "$part"; then
fail "$tool reported an error: $(head -n 1 "$part.err")"
fi
The dump command is stored in an array (dump_cmd), which keeps every argument intact, even one with spaces (lesson 104). Its output flows through a pipe straight into gzip, so the large uncompressed dump never touches the disk. The error messages of the dump tool go to a separate file, so the script can show the first line in its own message.
The if ! test relies on set -o pipefail: the pipeline's status is the status of the last command that failed, not only of gzip. Without pipefail, a failing mysqldump would be hidden, because gzip would still finish successfully on the empty input and return 0. This is the most common mistake in backup scripts, and it produces tidy-looking, empty backups.
Verifying the Backup
gzip -t -- "$part" 2>/dev/null || fail "the compressed file is damaged"
last=$(gzip -dc -- "$part" | tail -n 1)
[[ $last == "$trailer"* ]] || fail "the dump is incomplete (last line is '${last:0:40}')"
gzip -ttests the integrity of the compressed file without extracting it.- Each dump tool finishes a complete dump with a known last line.
mysqldumpwrites-- Dump completed on ...,pg_dumpwrites-- PostgreSQL database dump complete, and the SQLite dump ends withCOMMIT;. If the connection dies half-way, or the disk fills up, that line is missing. Thecasestatement at the start of the script stores the right line for each type in the variabletrailer. ${last:0:40}limits the quoted text in the error message to 40 characters.
A real restore test is still the best proof (see the end of this lesson), but these two checks catch the usual failures without needing a second database server.
Publishing Without Half-Written Files
The dump is first written to a hidden temporary file created with mktemp in the same directory as the final backup. Only after both checks have passed is it renamed:
part=$(mktemp "$outdir/.partial.XXXXXX")
trap 'rm -f -- "$part" "$part.err"' EXIT
...
mv -- "$part" "$final"
Renaming inside one file system is atomic. Another program that scans the backup directory, for example a copy job that uploads new files, will therefore never see a half-written backup under a real name. The EXIT trap (lesson 124) removes the temporary files when the script ends in any way, including after an error.
Locking With flock
exec 9> "$outdir/.dbbackup.lock"
flock -n 9 || die "another backup is already running" 3
exec 9> file opens the lock file on file descriptor 9 and keeps it open for the whole life of the script. flock -n 9 tries to take an exclusive lock without waiting (-n). If another instance holds it, the call fails and the script exits with status 3. The operating system releases the lock automatically when the script ends, even if it was killed, so there is no stale lock file to clean up. Lesson 171 explained lock files in more detail.
Rotation by File Name
The file name contains the date and time, dump_mysql_shop_20261202_174031.sql.gz, in a format that sorts alphabetically in the same order as chronologically. A glob (lesson 52) is expanded in sorted order, so the oldest backups come first:
d=[0-9]
old=("$outdir/dump_${type}_${name}_"$d$d$d$d$d$d$d$d"_"$d$d$d$d$d$d".sql.gz")
if (( ${#old[@]} > keep )); then
for f in "${old[@]:0:${#old[@]}-keep}"; do
rm -f -- "$f" "$f.sha256"
done
fi
- The pattern with eight digits, an underscore and six digits matches only real time stamps. Without it, a database called
shopwould also match the files of a database calledshop_eu, and the rotation of one database would delete the backups of the other. "${old[@]:0:${#old[@]}-keep}"is a slice of the array: everything except the lastkeepelements. The old dump and its checksum file are deleted together.
The new backup is made before any old backup is deleted. If the backup fails, the script exits earlier and all old backups remain.
The Complete Script
#!/usr/bin/env bash
#
# dbbackup.sh - back up one database to a compressed, verified dump file
#
# Usage: dbbackup.sh -t TYPE -d DATABASE [-o DIR] [-k KEEP] [-c CNF] [-q]
#
# Options:
# -t TYPE database type: mysql, postgres or sqlite
# -d DATABASE database name (for sqlite: path of the database file)
# -o DIR directory for the backups (default: ./db-backups)
# -k KEEP number of backups to keep per database (default: 7)
# -c CNF MySQL option file with the login (mode 600, see lesson text)
# -q quiet: print nothing except errors
# -h show this help
#
# PostgreSQL reads its password from ~/.pgpass or PGPASSFILE; no password is
# ever passed on the command line, where other users could see it with ps.
#
# Exit status: 0 backup made and verified, 1 backup failed, 2 usage error,
# 3 another backup is already running.
set -euo pipefail
export LC_ALL=C
umask 077 # backups contain data: owner-only files
readonly PROG=${0##*/}
usage() { sed -n '3,21s/^# \{0,1\}//p' "$0"; }
die() {
printf '%s: %s\n' "$PROG" "$1" >&2
exit "${2:-2}"
}
type= db= outdir=./db-backups keep=7 cnf= quiet=0
while getopts ':t:d:o:k:c:qh' opt; do
case $opt in
t) type=$OPTARG ;;
d) db=$OPTARG ;;
o) outdir=$OPTARG ;;
k) keep=$OPTARG ;;
c) cnf=$OPTARG ;;
q) quiet=1 ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
[[ -n $type && -n $db ]] || die "-t and -d are required (try -h)"
[[ $keep =~ ^[1-9][0-9]*$ ]] || die "-k needs a whole number of at least 1"
# Choose the dump command for this database type. Each type also has the last
# line a complete dump must end with, which is how the backup is verified.
case $type in
mysql)
tool=mysqldump
dump_cmd=("$tool" ${cnf:+--defaults-extra-file="$cnf"} --single-transaction --routines --triggers -- "$db")
trailer='-- Dump completed' ;;
postgres)
tool=pg_dump
dump_cmd=("$tool" --no-owner -- "$db")
trailer='-- PostgreSQL database dump complete' ;;
sqlite)
tool=sqlite3
[[ -f $db ]] || die "no such SQLite file: $db"
dump_cmd=("$tool" "$db" .dump)
trailer='COMMIT;' ;;
*) die "unknown database type '$type' (use mysql, postgres or sqlite)" ;;
esac
command -v "$tool" >/dev/null || die "$tool is not installed" 1
if [[ -n $cnf ]]; then
[[ -r $cnf ]] || die "cannot read $cnf"
perms=$(stat -c '%a' "$cnf")
(( (8#$perms & 8#077) == 0 )) || die "$cnf must not be readable by other users (chmod 600 $cnf)"
fi
mkdir -p "$outdir"
logfile=$outdir/dbbackup.log
log() {
printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >> "$logfile"
(( quiet )) || printf '%s\n' "$1"
}
# Only one backup at a time: a second run would compete for the database and the disk.
exec 9> "$outdir/.dbbackup.lock"
flock -n 9 || die "another backup is already running" 3
# Name: dump_TYPE_NAME_DATE.sql.gz. For SQLite the file name is used as NAME.
name=${db##*/}
stamp=$(date '+%Y%m%d_%H%M%S')
final=$outdir/dump_${type}_${name}_${stamp}.sql.gz
part=$(mktemp "$outdir/.partial.XXXXXX")
trap 'rm -f -- "$part" "$part.err"' EXIT
fail() {
log "FAILED: $1"
(( quiet )) && printf '%s: FAILED: %s\n' "$PROG" "$1" >&2 # errors are never silent
exit 1
}
log "backing up $type database '$name' to $final"
# 1. Dump and compress in one pipeline. With pipefail, an error in the dump
# command is not hidden by the success of gzip.
if ! "${dump_cmd[@]}" 2> "$part.err" | gzip -9 > "$part"; then
fail "$tool reported an error: $(head -n 1 "$part.err")"
fi
rm -f -- "$part.err"
# 2. Verify. An empty or damaged file is worse than no file, because it
# looks like a backup.
gzip -t -- "$part" 2>/dev/null || fail "the compressed file is damaged"
last=$(gzip -dc -- "$part" | tail -n 1)
[[ $last == "$trailer"* ]] || fail "the dump is incomplete (last line is '${last:0:40}')"
# 3. Publish: rename into place (atomic) and store a checksum next to it.
mv -- "$part" "$final"
( cd "$outdir" && sha256sum -- "${final##*/}" > "${final##*/}.sha256" )
size=$(stat -c '%s' "$final")
log "OK: ${final##*/} ($size bytes, verified)"
# 4. Retention: names contain the time stamp, so the glob is sorted oldest first.
# The digit pattern keeps database "shop" apart from a database "shop_eu".
d=[0-9]
old=("$outdir/dump_${type}_${name}_"$d$d$d$d$d$d$d$d"_"$d$d$d$d$d$d".sql.gz")
if (( ${#old[@]} > keep )); then
for f in "${old[@]:0:${#old[@]}-keep}"; do
rm -f -- "$f" "$f.sha256"
log "removed old backup ${f##*/}"
done
fi
Testing Without a Database Server
Testing a backup script against production databases is risky, and a test machine may not have a database server at all. A good technique (lesson 186) is to put a small fake program with the same name earlier in the PATH. The fake mysqldump below prints a tiny dump, records its arguments, and can simulate two kinds of failure:
#!/usr/bin/env bash
# fake mysqldump for tests: records its arguments, prints a tiny dump
echo "mysqldump $*" >> "${STUB_LOG:-/dev/null}"
case ${STUB_MODE:-ok} in
fail) echo "mysqldump: Got error: 1045: Access denied for user" >&2; exit 2 ;;
short) echo "-- partial dump"; echo "CREATE TABLE t (id int);"; exit 0 ;;
esac
echo "-- MySQL dump (fake)"
echo "CREATE TABLE users (id int, name varchar(20));"
echo "INSERT INTO users VALUES (1,'alice'),(2,'bob');"
echo "-- Dump completed on $(date '+%F %T')"
Save it as stubs/mysqldump with chmod +x, create a similar stubs/sqlite3, and run the tests with export PATH=$PWD/stubs:$PATH. The outputs below were produced this way. The PostgreSQL example uses the real pg_dump of the test machine, which had no server running.
Running the Backup
A Successful Backup
$ printf '[client]\nuser=backup\npassword=secret\n' > my.cnf
$ chmod 644 my.cnf
$ ./dbbackup.sh -t mysql -d shop -c my.cnf -o out; echo "status $?"
dbbackup.sh: my.cnf must not be readable by other users (chmod 600 my.cnf)
status 2
$ chmod 600 my.cnf
$ ./dbbackup.sh -t mysql -d shop -c my.cnf -o out; echo "status $?"
backing up mysql database 'shop' to out/dump_mysql_shop_20261202_174031.sql.gz
OK: dump_mysql_shop_20261202_174031.sql.gz (161 bytes, verified)
status 0
The first attempt shows the permission check: a world-readable password file is rejected. After chmod 600, the backup succeeds. The directory now contains the dump, its checksum and the log:
$ ls -l out
-rw------- 1 root root 184 Dec 2 17:40 dbbackup.log
-rw------- 1 root root 161 Dec 2 17:40 dump_mysql_shop_20261202_174031.sql.gz
-rw------- 1 root root 105 Dec 2 17:40 dump_mysql_shop_20261202_174031.sql.gz.sha256
All files are readable only by their owner, as promised by umask 077. The (hidden) lock file .dbbackup.lock is also in this directory.
What the Dump Tool Received
The log of the fake mysqldump shows exactly what the script passed to it:
$ cat stub.log
mysqldump --defaults-extra-file=my.cnf --single-transaction --routines --triggers -- shop
The password does not appear anywhere in the arguments, only the name of the option file. This is what ps would show to every user on the machine.
Failure Cases
A dump tool that fails, for example because of wrong credentials:
$ STUB_MODE=fail ./dbbackup.sh -t mysql -d shop -o out; echo "status $?"
backing up mysql database 'shop' to out/dump_mysql_shop_20261202_174038.sql.gz
FAILED: mysqldump reported an error: mysqldump: Got error: 1045: Access denied for user
status 1
A dump tool that exits normally but delivers an incomplete dump (a lost connection):
$ STUB_MODE=short ./dbbackup.sh -t mysql -d shop -o out; echo "status $?"
backing up mysql database 'shop' to out/dump_mysql_shop_20261202_174038.sql.gz
FAILED: the dump is incomplete (last line is 'CREATE TABLE t (id int);')
status 1
In both cases no file with a real backup name was created, and the temporary files were removed by the EXIT trap. The directory listing afterwards still holds only the earlier good backup. The real pg_dump without a server gives a similar result:
$ ./dbbackup.sh -t postgres -d nodb -o out; echo "status $?"
backing up postgres database 'nodb' to out/dump_postgres_nodb_20261202_174038.sql.gz
FAILED: pg_dump reported an error: pg_dump: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
status 1
In quiet mode (-q) the normal messages are suppressed, but errors still go to standard error, so a cron job that fails does not stay silent:
$ STUB_MODE=fail ./dbbackup.sh -q -t mysql -d shop -o out
dbbackup.sh: FAILED: mysqldump reported an error: mysqldump: Got error: 1045: Access denied for user
Backing Up SQLite
For SQLite the database name is the path of the file, and the file name part is used in the backup name:
$ ./dbbackup.sh -t sqlite -d app.db -o out; echo "status $?"
backing up sqlite database 'app.db' to out/dump_sqlite_app.db_20261202_174038.sql.gz
OK: dump_sqlite_app.db_20261202_174038.sql.gz (122 bytes, verified)
status 0
Two Backups at Once
While another instance holds the lock, a new run stops at once:
$ ./dbbackup.sh -t sqlite -d app.db -o out; echo "status $?"
dbbackup.sh: another backup is already running
status 3
Rotation
With five MySQL backups in the directory (four older ones and the first successful one) the command below makes a sixth and keeps only the three newest:
$ ./dbbackup.sh -t mysql -d shop -k 3 -o out
backing up mysql database 'shop' to out/dump_mysql_shop_20261202_174038.sql.gz
OK: dump_mysql_shop_20261202_174038.sql.gz (161 bytes, verified)
removed old backup dump_mysql_shop_20261125_010000.sql.gz
removed old backup dump_mysql_shop_20261126_010000.sql.gz
removed old backup dump_mysql_shop_20261127_010000.sql.gz
Input Errors
$ ./dbbackup.sh -t oracle -d x
dbbackup.sh: unknown database type 'oracle' (use mysql, postgres or sqlite)
$ ./dbbackup.sh -t mysql
dbbackup.sh: -t and -d are required (try -h)
$ ./dbbackup.sh -t sqlite -d nofile
dbbackup.sh: no such SQLite file: nofile
$ ./dbbackup.sh -t mysql -d x -k 0
dbbackup.sh: -k needs a whole number of at least 1
All of these exit with status 2.
Checking and Restoring a Backup
The checksum file lets you check later, for example after copying a backup to another server, that the file did not change. Run the check from the backup directory, because the checksum file contains the bare file name:
$ cd out && sha256sum -c dump_sqlite_app.db_20261202_174038.sql.gz.sha256
dump_sqlite_app.db_20261202_174038.sql.gz: OK
$ gzip -dc dump_sqlite_app.db_20261202_174038.sql.gz
BEGIN TRANSACTION;
CREATE TABLE notes (id integer, body text);
INSERT INTO notes VALUES(1,'hello');
COMMIT;
To restore, send the dump to the matching client. These commands do not belong to the script; run them on a spare database, never on the production one:
gzip -dc dump_mysql_shop_20261202_174031.sql.gz | mysql shop_restored
gzip -dc dump_postgres_shop_20261202_174031.sql.gz | psql shop_restored
gzip -dc dump_sqlite_app.db_20261202_174038.sql.gz | sqlite3 restored.db
Do this on a schedule as well. A monthly restore into a scratch database, followed by a simple query such as counting the rows of an important table, is the only test that proves the backup can really be used.
Scheduling
This crontab (lesson 170) backs up two databases every night at 02:30 and keeps two weeks of history. With -q, only failures produce output, and cron mails any output to the account owner:
30 2 * * * /usr/local/bin/dbbackup.sh -q -t mysql -d shop -c /etc/dbbackup/shop.cnf -o /srv/backups/db -k 14
40 2 * * * /usr/local/bin/dbbackup.sh -q -t postgres -d crm -o /srv/backups/db -k 14
The two jobs start ten minutes apart, so they do not compete for disk and CPU. Add || /usr/local/bin/notify.sh "Backup failed on $(hostname)" (lesson 173) if you prefer a message to a mail. The backup directory should be on a different disk or a different machine than the database; a copy that lives on the same disk is lost with it. A second job that copies the directory elsewhere with rsync completes the plan.
Ideas for Extending the Project
- Encryption. Pipe the output through
gpg --encrypt --recipient ...before it is stored, so copies on remote storage cannot be read by whoever finds them. - All databases. Loop over the output of
mysql -N -e 'SHOW DATABASES'orpsql -Atc 'SELECT datname FROM pg_database WHERE NOT datistemplate'and call the script once per database. - Automatic restore test. After the backup, load the dump into a temporary SQLite or scratch database, run a row-count query, and report the result in the log.
- Remote copy. Add
rsync -a --partial "$final" backup@host:/srv/backups/after verification and treat a failed copy as a failed backup. - Disk space check. Compare the size of the last backup with the free space (lesson 166) before starting and stop with a clear message if the new dump will not fit.