BASH Script for WordPress Backups

A lot of people are worried about backing up their WordPress installs on a regular basis. I know. I get that. Here’s a script you can use if you have access to the shell. Put this sucker on cron (For many Linux distributions, you can put it in

1
/etc/cron.daily

if you have root access. Otherwise, use whatever mechanism your hosting provider offers for cronjobs/scheduled tasks.

Also note that while this script will work fine for most Linux distributions, you should know that every distribution is different and minor modifications may be necessary.

Standard Disclaimer: This script is free of charge and, thus, unsupported. Functionality is neither guaranteed nor implied. I work as a consultant and have many years making WordPress work for companies and individuals. If you want support, you have to pay but I’d be happy to work with you. Contact me for paid work only at aaron@technosailor.com.

With all that done, here’s the script. Make sure you remember to edit the appropriate variables and make it executable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/bin/bash
#### DO NOT EDIT
DATE=`date +-%y-%m-%d--%T`

#### EDIT BELOW

# If CREATE_ZIP is 0, then a tarball will be used (default). If 1, then a zip file will be used
CREATE_ZIP=0
# Accessible/writable directory for temp storage
TMPDIR=/tmp
# Absolute path to WordPress backup storage location
WPBACKUP=/backups
# Absolute path to WordPress install.
WPDIR=/path/to/wordpress
# Enter Database connection details from your wp-config.php file
WP_DBUSER=user
WP_DBPASS=password
WP_DBHOST=localhost
WP_DBNAME=dbname

#### STOP EDITING
if [ ! -d $TMPDIR ]; then
    mkdir $TMPDIR/backup
fi

if [ ! -d $WPBACKUP ]; then
    mkdir $WPBACKUP
fi

# Dumps the database
mysqldump -h$WP_DBHOST -u$WP_DBUSER -p$WP_DBPASS $WP_DBNAME > $TMPDIR/backup/wordpress-db.sql
 
# Create Archive
if [[ CREATE_ZIP -eq 0 ]]; then
    # Tarballs the Database and WP files
    tar -cvf $TMPDIR/backup/backup$DATE.tar $WPDIR/.htaccess $WPDIR/wp-content $TMPDIR/backup/wordpress-db.sql 2>&1
    gzip $TMPDIR/backup/backup$DATE.tar
    # Move archive to backup location
    mv $TMPDIR/backup/backup$DATE.tar.gz $WPBACKUP/
else
    # Zips the database and WP files
    zip $TMPDIR/backup/backup$DATE.zip $WPDIR/.htaccess $WPDIR/* $TMPDIR/backup/wordpress-db.sql 2>&1
    # Move archive to backup location
    mv $TMPDIR/backup/backup$DATE.zip $WPBACKUP/
fi