Skip to content

Instantly share code, notes, and snippets.

@tva77
Last active August 12, 2023 21:16
Show Gist options
  • Save tva77/0164a8e680e92f5661f68f637125cad2 to your computer and use it in GitHub Desktop.
Save tva77/0164a8e680e92f5661f68f637125cad2 to your computer and use it in GitHub Desktop.
wordpress clone shell script
#!/bin/bash
# shell script to clone a wordpress installation on the same server, to another subdomain
# Source Settings
SOURCE_DIR="/var/www/vhosts/yourdomain.com/subdomain1.yourdomain.com/httpdocs"
SOURCE_DB_NAME="source_db_name"
SOURCE_DB_USER="source_db_user"
SOURCE_DB_PASS="source_db_pass"
SOURCE_SUBDOMAIN="subdomain1.yourdomain.com"
# Destination Settings
DEST_DIR="/var/www/vhosts/yourdomain.com/subdomain2.yourdomain.com/httpdocs"
DEST_DB_NAME="dest_db_name"
DEST_DB_USER="dest_db_user"
DEST_DB_PASS="dest_db_pass"
DEST_SUBDOMAIN="subdomain2.yourdomain.com"
# Database Table Prefix (this is often 'wp_' by default, but may vary)
PREFIX="wp_"
# Ensure destination directory is present
mkdir -p "$DEST_DIR"
# Copy files
rsync -av --delete "$SOURCE_DIR/" "$DEST_DIR/"
# Update wp-config.php with the new database settings
sed -i "s/'DB_NAME', '$SOURCE_DB_NAME'/'DB_NAME', '$DEST_DB_NAME'/g" "$DEST_DIR/wp-config.php"
sed -i "s/'DB_USER', '$SOURCE_DB_USER'/'DB_USER', '$DEST_DB_USER'/g" "$DEST_DIR/wp-config.php"
sed -i "s/'DB_PASSWORD', '$SOURCE_DB_PASS'/'DB_PASSWORD', '$DEST_DB_PASS'/g" "$DEST_DIR/wp-config.php"
# Dump source database
mysqldump -u"$SOURCE_DB_USER" -p"$SOURCE_DB_PASS" "$SOURCE_DB_NAME" > /tmp/source_db.sql
# Create a new database for the destination
mysql -u"$DEST_DB_USER" -p"$DEST_DB_PASS" -e "DROP DATABASE IF EXISTS $DEST_DB_NAME; CREATE DATABASE $DEST_DB_NAME;"
# Import into the destination database
mysql -u"$DEST_DB_USER" -p"$DEST_DB_PASS" "$DEST_DB_NAME" < /tmp/source_db.sql
# Replace URLs in the database
mysql -u"$DEST_DB_USER" -p"$DEST_DB_PASS" "$DEST_DB_NAME" <<EOF
UPDATE ${PREFIX}options SET option_value = REPLACE(option_value, '$SOURCE_SUBDOMAIN', '$DEST_SUBDOMAIN') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE ${PREFIX}posts SET post_content = REPLACE(post_content, '$SOURCE_SUBDOMAIN', '$DEST_SUBDOMAIN');
UPDATE ${PREFIX}postmeta SET meta_value = REPLACE(meta_value, '$SOURCE_SUBDOMAIN', '$DEST_SUBDOMAIN');
UPDATE ${PREFIX}comments SET comment_content = REPLACE(comment_content, '$SOURCE_SUBDOMAIN', '$DEST_SUBDOMAIN');
EOF
# Remove the temporary database dump
rm /tmp/source_db.sql
echo "Cloning finished."
@tva77
Copy link
Author

tva77 commented Aug 12, 2023

shell script to clone a wordpress installation on the same server, to another subdomain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment