Skip to content

Instantly share code, notes, and snippets.

@gsarig
Created December 25, 2023 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsarig/cea971b6ec60230b1fee55aa6bba291e to your computer and use it in GitHub Desktop.
Save gsarig/cea971b6ec60230b1fee55aa6bba291e to your computer and use it in GitHub Desktop.
Run WP-CLI commands on multiple sites
#!/bin/bash
# A bash script to run WP-CLI commands on multiple sites at once. It requires WP-CLI, obviously (https://wp-cli.org/).
# The script will search for all WordPress installations under a given directory and will run the command. 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 superwp.sh`. Then, include it to `.bashrc` or `.bash_profile` by adding `source path/to/superwp.sh`.
# Then, you can run any `wp` command you like on all the sites of your server, by replacing `wp` with `superwp`.
# Example: `superwp plugin list`.
# 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
superwp() {
# 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
# In case $1 contained a path, we should remove it from the wp command
if [ -d "$1" ]; then
dir=$1
shift
else
dir="$BASEPATH"
fi
# $@ stores all the command line arguments
wp_command=$@
# Iterate over all folders under the given parent directory
for d in $dir/* ; do
# Determine correct directory depending on whether BASEPATH is default
wp_dir="$d"
if [ "$dir" = "$BASEPATH" ]; then
wp_dir="$d/htdocs"
fi
# Check if the folder is indeed a WordPress installation by searching for a wp-config.php file
if [ -f $d/wp-config.php ]; then
echo -e "\e[32mRunning in $d\e[0m"
# Update core
sudo /usr/local/bin/wp --path="$wp_dir" $wp_command
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment