Skip to content

Instantly share code, notes, and snippets.

@gsarig
Last active January 28, 2021 15:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsarig/df16f1896706910532a7661abad00898 to your computer and use it in GitHub Desktop.
Save gsarig/df16f1896706910532a7661abad00898 to your computer and use it in GitHub Desktop.
Batch backup a server's WordPress databases with WP-CLI (read more at: https://www.gsarigiannidis.gr/wp-cli-batch-backup-wordpress-databases/)
#!/bin/bash
# A bash script to batch backup a server's WordPress databases with WP-CLI. It requires WP-CLI, obviously (https://wp-cli.org/).
# The script will search for all WordPress installations under a given directory and will backup their databases. You can declare more than one such directories.
# You don't have to modify the script every time you add a new site. As long as the new site is under a declared parent directory, its database will be backed up.
# After creating the file, don't forget to make it executable by doing:
# chmod +x wp-cli_batch_db_backup.sh
# Also, you might want to add this in a cron job for scheduled backups.
# Set PATH environment variable
export PATH="/usr/local/bin:/usr/bin:/bin"
# The base path on your server (you might need to change that)
BASEPATH=/var/www
# We use a function, in order to be able to call it as many times as we want, for as many different directories containing WordPress installations there are on the server
update_databases() {
# Iterate over all folders under the given parent directory
for d in $1/* ; do
# Check if the folder is indeed a WordPress installation by searching for a wp-config.php file
if [ -f $d/wp-config.php ]; then
# Set the name of the backup directory
BACKUPDIR=$d/db-backup
# Create the db-backup directory, if it doesn't exist
[ -d ${BACKUPDIR} ] || sudo mkdir ${BACKUPDIR}
# Backup the database using WP-CLI
sudo /usr/local/bin/wp --path="$d" --allow-root --quiet db export ${BACKUPDIR}/db-backup.sql
# Set folder permissions to prevent direct access to the backup file
chmod -R 770 ${BACKUPDIR}
fi
done
}
# Call the function giving as a parameter the path to the directory containing your WordPress installations (you might need to change that)
update_databases ${BASEPATH}
# If you keep your sites organized in folders or if you have WordPress installations on various different paths on your server, call the function for each parent folder like so:
# update_databases ${BASEPATH}/folder1
# update_databases ${BASEPATH}/folder2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment