Created
June 6, 2014 11:25
-
-
Save figa12/a3b6ab1189073c55d027 to your computer and use it in GitHub Desktop.
This script will copy a database. It is much faster than doing a mysqldump and then inserting it to a new database, since it requires no downloading/uploading. It will also create a user called "testuser" that has all permissions on the new database. (testuser has the password: testuser). Remeber to set DBUSER, DBPASS, DBHOST, DB_OLD, and DB_NEW.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
DBUSER="username"; | |
DBPASS="password"; | |
DBHOST="localhost"; | |
DB_OLD=database | |
DB_NEW=database_new | |
DBCONN="--host=${DBHOST} --user=${DBUSER} --password=${DBPASS}"; | |
MYSQL_CREATE='set foreign_key_checks = 0'; | |
MYSQL_INSERT='set foreign_key_checks = 0'; | |
echo "Begin database clone (may take a while)"; | |
echo "-- Create destination database"; | |
echo "DROP DATABASE IF EXISTS ${DB_NEW}; CREATE DATABASE ${DB_NEW}" | mysql ${DBCONN}; | |
[ $? -ne 0 ] && exit $?; | |
echo "-- Select source table schemas"; | |
MYSQL_TABLES=$(echo "SHOW TABLES" | mysql $DBCONN $DB_OLD | tail -n +2); | |
[ $? -ne 0 ] && exit $?; | |
COUNT=1 | |
for TABLE in $MYSQL_TABLES; do | |
MYSQL_INSERT="${MYSQL_INSERT}; ALTER TABLE ${DB_NEW}.${TABLE} DISABLE KEYS"; | |
MYSQL_INSERT="${MYSQL_INSERT}; INSERT INTO ${DB_NEW}.${TABLE} SELECT * FROM ${DB_OLD}.${TABLE}"; | |
MYSQL_INSERT="${MYSQL_INSERT}; ALTER TABLE ${DB_NEW}.${TABLE} ENABLE KEYS"; | |
MYSQL_CREATE="${MYSQL_CREATE}; $(echo SHOW CREATE TABLE ${TABLE}|mysql -B -r ${DBCONN} ${DB_OLD}|tail -n +2|cut -f 2-)"; | |
[ $? -ne 0 ] && echo && exit $?; | |
[ $COUNT -le 1 ] && echo -n " [ "; | |
echo -n "."; | |
[ $COUNT -ge 65 ] && echo " ]" && COUNT=0; | |
COUNT=$((COUNT+1)) | |
done; | |
MYSQL_CREATE="${MYSQL_CREATE}; set foreign_key_checks = 1"; | |
MYSQL_INSERT="${MYSQL_INSERT}; set foreign_key_checks = 1"; | |
[ $COUNT -gt 1 ] && echo " ]"; | |
echo "-- Create destination table schemas"; | |
echo "${MYSQL_CREATE};" | mysql $DBCONN $DB_NEW | |
[ $? -ne 0 ] && exit $?; | |
echo "-- Insert source data into destination tables"; | |
echo "${MYSQL_INSERT};" | mysql $DBCONN $DB_NEW | |
echo "-- Creating user: testuser"; | |
echo "GRANT ALL PRIVILEGES ON ${DB_NEW}.* TO 'testuser'@'localhost' IDENTIFIED BY 'testuser';" | mysql ${DBCONN}; | |
[ $? -ne 0 ] && exit $?; | |
echo "Done."; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment