Skip to content

Instantly share code, notes, and snippets.

@bradt
Last active November 22, 2018 16:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bradt/9cfe978c0772ae064ac9 to your computer and use it in GitHub Desktop.
Save bradt/9cfe978c0772ae064ac9 to your computer and use it in GitHub Desktop.
Simple Remote Backups for WordPress
#!/bin/bash
BUCKET_NAME=${1-''}
# Get upload folder path using WP-CLI
# We use --url=http://blah.com in our WP-CLI commands so that we don't get the PHP warning about HTTP_HOSTS
UPLOADS_PATH=$(wp eval '$upload_dir = wp_upload_dir(); echo $upload_dir["basedir"];' --url=http://blah.com 2>&1)
if [[ $UPLOADS_PATH =~ Error ]]
then
echo "This script must be run from inside a WordPress installation folder."
exit
fi
if [ ! -d ../backups/ ]
then
echo "This script requires a 'backups' folder 1 level up from your WordPress installation folder."
exit
fi
NOW=$(date +%Y%m%d%H%M%S)
SQL_FILE=${NOW}_database.sql
UPLOADS_FILE=${NOW}_uploads.tar.gz
CONTENT_PATH=$(dirname $UPLOADS_PATH)
UPLOADS_DIRNAME=$(basename $UPLOADS_PATH)
# Backup database
wp db export ../backups/$SQL_FILE --add-drop-table --quiet --url=http://blah.com
cd ../backups/
# Compress the database dump file
gzip $SQL_FILE
# Backup uploads directory
tar -zcf $UPLOADS_FILE --directory=$CONTENT_PATH $UPLOADS_DIRNAME
# Remove backup files that are a month old
# If running on OS X, the date command is a bit different:
# rm -f $(date -v-1m +%Y%m%d*).gz
rm -f $(date +%Y%m%d* --date='1 month ago').gz
# Copy files to S3 if bucket given
if [ ! -z $BUCKET_NAME ]
then
aws s3 cp $SQL_FILE.gz s3://$BUCKET_NAME/ --quiet --storage-class REDUCED_REDUNDANCY
aws s3 cp $UPLOADS_FILE s3://$BUCKET_NAME/ --quiet --storage-class REDUCED_REDUNDANCY
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment