Skip to content

Instantly share code, notes, and snippets.

@DrizzlyOwl
Created April 7, 2022 15:46
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 DrizzlyOwl/d9e01f185d5a2d60be835b1e0ea08e43 to your computer and use it in GitHub Desktop.
Save DrizzlyOwl/d9e01f185d5a2d60be835b1e0ea08e43 to your computer and use it in GitHub Desktop.
Migrate a database from one MySQL host to another
#! /bin/bash
# @author Ash Davies <a.davies@mixd.co.uk>
FROM=$1
TO=$2
FILENAME=wp-config.php
BACKUP_FIRST=yes
TMP=$(mktemp)
# Terminate on any errors
set -e
echo "[!] WARNING"
echo "[!] Please ensure you have already created the new database on your target host before continuing"
echo "[!] This script does not accommodate creation of new databases. It will simply export/import from old to new"
echo
echo
asksure() {
echo -n "Are you sure you want to continue (Y/N)? "
echo
while read -r -n 1 -s answer; do
if [[ $answer = [YyNn] ]]; then
[[ $answer = [Yy] ]] && retval=0
[[ $answer = [Nn] ]] && retval=1
break
fi
done
echo
return $retval
}
searchreplace() {
str=$(sed --version 2> /dev/null | head -n 1);
sub="GNU Sed";
#bin=$(command -v 'sed' || which 'sed' || type -p 'sed');
pattern="s/$1/$2/g"
echo "Performing search and replace pattern '$pattern' on '$3'"
#if [[ "$str" == *"$sub"* ]]; then
# $bin -i $pattern $3
#else
# $bin -i '' $pattern $3
#fi
sed -i --follow-symlinks $pattern $3
echo
}
backup_db() {
echo "Creating database backup from old host"
echo "[i] $(wp db export $TMP)"
echo
}
push_db() {
echo "Importing database backup to new host"
echo "[i] $(wp db import $TMP)"
echo
}
cleanup() {
echo "Deleting previous backup"
rm $TMP
echo
echo "Disabling maintenance mode"
rm $(pwd -P)/wordpress/.maintenance
echo
}
scandir() {
echo "Scanning $(pwd -P) for files that match '$FILENAME'"
ls $(pwd -P) | grep -w "$FILENAME" &> /dev/null;
if [ "$?" = "0" ];
then
FILE="$(pwd -P)/$FILENAME"
echo "[i] Found $FILE"
echo
# if grep -q "DB_HOST.*[\"']\K$FROM(?=[\"'])" $FILE;
if grep -q $FROM $FILE;
then
echo "Found reference to old db host '$FROM'"
echo
echo "Creating wp-config.php backup"
echo "[i] $(cp -nfv $FILE{,.old.php})"
echo
echo "Enabling maintenance mode"
touch $(pwd -P)/wordpress/.maintenance
echo "<?php \$upgrading = time(); ?>" > $(pwd -P)/wordpress/.maintenance
backup_db
searchreplace $FROM $TO $FILE
push_db
cleanup
else
echo "Error: Cannot find reference to old db host"
exit 1
fi
else
echo "Can't find any files"
exit 1
fi
}
if [ -z "$2" ]
then
echo "Error: Please specify the database hostnames as arguments wrapped in quotes"
exit 1
fi
echo "I'm going to look for all references of '$FROM' and replace it with '$TO'."
if asksure;
then
scandir;
else
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment