Last active
May 16, 2019 00:47
-
-
Save markasoftware/e3deec5c993121bd0b27d7c7e2cab86e to your computer and use it in GitHub Desktop.
Wordpress Backup (DB + Files)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# USAGE: | |
# `backup-wordpress user@host /sth/backups-dir` (usually root) | |
# optional environment variables: | |
# WP_DB: Name of the wordpress database (default: wordpress). | |
# WP_DB_USER: User for the mysql database (default: root). | |
# WP_DB_PASSWORD: Password for mysql database (defaults to prompting). | |
# WP_WWW: Path to the wordpress files (remotely). Should be direct to the `wordpress` directory, not the general public html one (default: /var/www/wordpress). | |
set -e | |
if [ $# -lt 2 ]; then | |
echo "USAGE: backup-wordpress user@host /sth/backups-dir" | |
exit 1 | |
fi | |
ssh_target=$1 | |
backups_dir=${2%/} | |
if ! [ -d "$backups_dir" ]; then | |
echo "Backups directory doesn't exist!" | |
exit 1 | |
fi | |
if [ -z "$WP_DB_PASSWORD" ]; then | |
echo -n 'Database password: ' | |
read WP_DB_PASSWORD | |
fi | |
WP_WWW=${WP_WWW:-/var/www/wordpress} | |
WP_WWW=${WP_WWW%/} | |
backup_file="$backups_dir/$(date -Iminutes).tar.gz" | |
echo 'Connecting to remote host.' | |
remote_tar=$(ssh "$ssh_target" mktemp 2>/dev/null) | |
ssh "$ssh_target" 'bash -s' 2>/dev/null <<EOF | |
echo 'Dumping database.' | |
remote_db_dump=\$(mktemp) | |
mysqldump --user '${WP_DB_USER:-root}' --password '${WP_DB:-wordpress}' <<< '$WP_DB_PASSWORD' > "\$remote_db_dump" | |
echo 'Compressing backup.' | |
tar czf '$remote_tar' -C "\$(dirname "\$remote_db_dump")" "\$(basename "\$remote_db_dump")" -C "\$(dirname '$WP_WWW')" "\$(basename '$WP_WWW')" | |
rm -f '$remote_db_dump' | |
EOF | |
echo 'Transferring backup to local machine.' | |
rsync -t --info=progress2 --remove-source-files "$ssh_target:$remote_tar" "$backup_file" | |
echo "Backup complete. Size: $(du -hs "$backup_file")" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment