#!/bin/bash
# === Configuration ===
WP_PATH="/var/www/html" # Path to your WordPress install
OLD_URL="https://staging.example.com"
NEW_URL="https://www.example.com"
# === Navigate to the WP install directory ===
cd "$WP_PATH" || { echo "❌ Error: WP path not found"; exit 1; }
# === Step 1: Dry run to preview changes ===
echo "🔍 Running dry run search-replace..."
wp search-replace "$OLD_URL" "$NEW_URL" \
--all-tables \
--precise \
--recurse-objects \
--skip-columns=guid \
--dry-run
echo ""
read -p "Do you want to proceed with the actual replacement? (y/n): " CONFIRM
if [[ "$CONFIRM" != "y" ]]; then
echo "❌ Replacement aborted."
exit 0
fi
# === Step 2: Perform the actual search-replace ===
echo "⚙️ Performing live replacement..."
wp search-replace "$OLD_URL" "$NEW_URL" \
--all-tables \
--precise \
--recurse-objects \
--skip-columns=guid
echo "✅ URL replacement complete."
How to Create and Execute This Script
Follow these steps to create and run your WordPress script:
Open Your Terminal
Connect to your server via SSH or open your local terminal.
Create the Script File
Use a text editor like nano to create a new file. For example:
$ nano my-script.sh
Paste the Script Code
Copy the full script from above and paste it into the terminal. Once done:
- Press CTRL+O to save
- Press Enter to confirm the filename
- Press CTRL+X to exit nano
Make the Script Executable
$ chmod +x my-script.sh
Run the Script
$ ./my-script.sh
⚠️ Backup First!
Use our handy script to run a full backup prior to using this script.
Requirements
- WP-CLI must be installed and accessible from the shell.
- wp-config.php must be correctly configured (WP-CLI uses it to access the DB).
- Run this script as a user with permission to access the WP directory and write to the backup folder.