WordPress Backup Scripts

backup-wordpress-dir.sh

  • Assume wordpress directory set up in /var/www/<domain>/wordpress format
#!/bin/bash
set -eo pipefail

site=$1
if [[ -z ${site} ]]; then
    echo "Usage: $0 <site>"
    exit 1
fi

set -u
src_wp_dir="/var/www/${site}/wordpress"

date_str="$(date '+%F')"
rand_lower="$(set +o pipefail; tr -cd "[:lower:]" </dev/urandom | head -c 4)"
bak_dir="/home/$USER/wordpress-backup/${date_str}-${rand_lower}"
bak_wp_dir="${bak_dir}/${site}/wordpress"

mkdir -p "${bak_wp_dir}"
cleanup() {
    if [[ ! -f "${bak_wp_dir}/../wordpress.tgz" ]]; then
        sudo rm -rf "${bak_dir}"
    fi
    sudo rm -rf "${bak_wp_dir}"
}
trap cleanup EXIT

echo "Backing up ${src_wp_dir}"
sudo rsync -ah ${src_wp_dir}/ ${bak_wp_dir}/
cd -- ${bak_wp_dir}/..
sudo tar czf wordpress.tgz wordpress/
echo "Backup file: $(du -h $(pwd)/wordpress.tgz)"

backup-wordpress-site.sh

  • Assume wordpress directory is under /home/$USER/<domain> for shared hosting like DreamHost.
#!/bin/bash
set -eo pipefail

site=$1
if [[ -z ${site} ]]; then
    echo "Usage: $0 <site>"
    exit 1
fi

set -u
src_wp_dir="/home/$USER/${site}"

date_str="$(date '+%F')"
rand_lower="$(set +o pipefail; tr -cd "[:lower:]" </dev/urandom | head -c 4)"
bak_dir="/home/$USER/wordpress-backup/${date_str}-${rand_lower}"
bak_wp_dir="${bak_dir}/${site}"

mkdir -p "${bak_wp_dir}"
cleanup() {
    if [[ ! -f "${bak_dir}/${site}.tgz" ]]; then
        rm -rf "${bak_dir}"
    fi
    rm -rf "${bak_wp_dir}"
}
trap cleanup EXIT

echo "Backing up ${src_wp_dir}"
rsync -ah ${src_wp_dir}/ ${bak_wp_dir}/
cd -- ${bak_dir}/
tar czf ${site}.tgz ${site}/
echo "Backup file: $(du -h ${bak_dir}/${site}.tgz)"

backup-database.sh

#!/bin/bash
set -eo pipefail

dbhost=$1
dbname=$2
dbuser=$3
dbpass=$4
backupdir=$5

set -u

if [[ $# -ne 5 ]]; then
    echo "Usage
    $0 <dbhost> <dbname> <dbuser> <dbpass> <backupdir>
    "
    exit 1
fi

if [[ ! -e ${backupdir} ]]; then
    mkdir -p ${backupdir}
fi

if [[ ! -d ${backupdir} ]]; then
    echo "${backupdir} is not directory!"
    exit 1
fi

backupfile="${backupdir}/${dbname}-$(date +%F_%s).sql"

mysqldump --add-drop-table -h${dbhost} -u${dbuser} -p${dbpass} ${dbname} > ${backupfile}
gzip ${backupfile}

echo "Backup: $(du -h ${backupfile}.gz)"

restore-database.sh

#!/bin/bash
set -eo pipefail

dbhost=$1
dbname=$2
dbuser=$3
dbpass=$4
dbfile=$5

set -u

if [[ $# -ne 5 || ! ${dbfile} =~ (.sql|.sql.gz)$ ]]; then
    echo "Usage:
    $0 <dbhost> <dbname> <dbuser> <dbpass> path/to/filename.sql
    $0 <dbhost> <dbname> <dbuser> <dbpass> path/to/filename.sql.gz
    "
    exit 1
fi

if [[ ! -f ${dbfile} ]]; then
    echo "file not found: ${dbfile}"
    exit 1
fi

if [[ ${dbfile} =~ .sql.gz$ ]]; then
    gzfile=${dbfile}
    sqlfile=${gzfile%%.gz}
    gunzip ${gzfile}
elif [[ ${dbfile} =~ .sql$ ]]; then
    sqlfile=${dbfile}
fi

mysql -h${dbhost} -u${dbuser} -p${dbpass} ${dbname} < ${sqlfile}

Leave a Comment

Your email address will not be published.

fifteen − 5 =