Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Migrate a WordPress sql script from one domain to another
#!/bin/bash
# mysqldump your product database to database_name_here.sql
# transfer it to this file's directory on another server
# copy wordpres_migrate.yml to this file's directory and update the variables
# usage: wordpress_migrate.sh [config.yml]
die () {
echo >&2 "$@"
exit 1
}
# @param **optional** custom config file
# default is script_name.yml e.g. wordpress_migrate.yml
CONFIG=$1
if [ ! $CONFIG ]; then
# @link http://stackoverflow.com/questions/192319/how-do-i-know-the-script-file-name-in-a-bash-script
# @link http://stackoverflow.com/questions/125281/how-do-i-remove-the-file-suffix-and-path-portion-from-a-path-string-in-bash
# remove path
FILE="${0##*/}"
# remove script extension, add '.yml'
CONFIG="${FILE%.*}.yml"
fi
[ -f "$CONFIG" ] || die "Couldn't find $CONFIG in current directory. Exiting."
# @link http://stackoverflow.com/questions/5014632/how-can-i-parse-a-yaml-file-from-a-linux-shell-script
eval $(sed -e 's/:[^:\/\/]/="/g;s/$/"/g;s/ *=/=/g' $CONFIG)
[ -f "$DB_NAME.sql" ] || die "Couldn't find $DB_NAME.sql in current directory. Exiting."
mysql -u"$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" < "$DB_NAME.sql"
WP_OPTIONS_SQL="UPDATE wp_options SET option_value = '$TO_HOME' WHERE option_name = 'home'; UPDATE wp_options SET option_value = '$TO_SITEURL' WHERE option_name = 'siteurl';"
WP_POSTS_SQL="UPDATE wp_posts SET guid = REPLACE(guid, '$FROM_HOME', '$TO_HOME') WHERE guid LIKE '$FROM_HOME%';"
WP_OPTIONS_CHECK_SQL="SELECT option_name, option_value FROM wp_options WHERE option_name IN('home', 'siteurl');"
mysql -u"$DB_USER" -p"$DB_PASSWORD" -e"$WP_OPTIONS_SQL" "$DB_NAME"
mysql -u"$DB_USER" -p"$DB_PASSWORD" -e"$WP_POSTS_SQL" "$DB_NAME"
mysql -u"$DB_USER" -p"$DB_PASSWORD" -e"$WP_OPTIONS_CHECK_SQL" "$DB_NAME"
FROM_HOME : http://www.mydomain.com
TO_HOME : http://stage.mydomain.com
FROM_SITEURL : http://www.mydomain.com/wp
TO_SITEURL : http://stage.mydomain.com/wp
DB_NAME : database_name_here
DB_USER : username_here
DB_PASSWORD : password_here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment