Skip to content

Instantly share code, notes, and snippets.

Last active January 28, 2021 15:07
What would you like to do?
Batch backup a server's WordPress databases with WP-CLI (read more at:
# A bash script to batch backup a server's WordPress databases with WP-CLI. It requires WP-CLI, obviously (
# 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
# 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)
# 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
# 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}
# 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