Skip to content

Instantly share code, notes, and snippets.

@phillip-boombox
Created June 27, 2018 18:04
Show Gist options
  • Save phillip-boombox/6d6c248547ac0605e3e47c509b783b3a to your computer and use it in GitHub Desktop.
Save phillip-boombox/6d6c248547ac0605e3e47c509b783b3a to your computer and use it in GitHub Desktop.
BASH script to make a backup of website files and the database. Useful as a CRON script.
#!/bin/bash
# This script creates a compressed backup archive of the given directory and the given MySQL table. More details on implementation here: http://theme.fm
# Feel free to use this script wherever you want, however you want. We produce open source, GPLv2 licensed stuff.
# Author: Konstantin Kovshenin exclusively for Theme.fm in June, 2011
# Original link: https://theme.fm/a-shell-script-for-a-complete-wordpress-backup/
# Set the date format, filename and the directories where your backup files will be placed and which directory will be archived.
NOW=$(date +"%Y-%m-%d-%H%M")
FILE="yourdomain.com.$NOW.tar"
BACKUP_DIR="/some_accessible_location/backups"
WWW_DIR="/some_folder_to_back_up/"
# MySQL database credentials
DB_USER="username"
DB_PASS="password"
DB_NAME="database"
DB_HOST="hostname"
DB_FILE="yourdomain.com.$NOW.sql"
# Tar transforms for better archive structure.
WWW_TRANSFORM='s,^some_folder_to_back_up,html,'
DB_TRANSFORM='s,^some_accessible_location/backups,database,'
### Stop Editing Here ###
# Use these to prevent the "tar: Removing leading '/' from member names" STDERR.
# Useful if script is run in a CRON so it doesn't email that message.
# Creates a path string without the leading slash using the above vars
# link: http://lichao.net/eblog/resolve-tar-removing-leading-from-member-names-error-message-201408895.html
BACKUP_DIR_REL=${BACKUP_DIR:1} # Remove first character. Requires BASH >= 4.2
WWW_DIR_REL=${WWW_DIR:1} # Remove first character. Requires BASH >= 4.2
# Create the archive and the MySQL dump
tar -cf $BACKUP_DIR/$FILE --transform $WWW_TRANSFORM -C / $WWW_DIR_REL
mysqldump -u $DB_USER -p$DB_PASS $DB_NAME -h $DB_HOST > $BACKUP_DIR/$DB_FILE
# Append the dump to the archive, remove the dump and compress the whole archive.
tar --append --file=$BACKUP_DIR/$FILE --transform $DB_TRANSFORM -C / $BACKUP_DIR_REL/$DB_FILE
rm $BACKUP_DIR/$DB_FILE
gzip -9 $BACKUP_DIR/$FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment