DB sync script

Discussion in 'Tips/Tricks/Mods' started by ikrudolf, Feb 18, 2015.

  1. ikrudolf

    ikrudolf Member

    I use this script to copy the DB's form and "OLD" server to the "NEW" server.
    I executed the scipt once, but I want to run it again but it sais access denied because the DB's are already created.
    Can somebody help me to change the script so it will drop existing DB's and copies it again?

    Code:
    #!/bin/bash
    # where your mysql commands are
    CMD_MYSQL="/usr/bin/mysql"
    CMD_MYSQLDUMP="/usr/bin/mysqldump"
    
    # login credentials of the OLD server side
    DB_USER_FROM="root"
    DB_PASS_FROM="password"
    DB_HOST_FROM="localhost"
    
    # login credentials of the NEW server side
    DB_USER_TO="root"
    DB_PASS_TO="password"
    DB_HOST_TO="192.168.2.159" # IP of target server...
    
    # index all databases on the local (submitting) side
    echo "database sync"
    DATABASES=`echo "SHOW DATABASES;" | ${CMD_MYSQL} -p${DB_PASS_FROM} -u ${DB_USER_FROM} -h ${DB_HOST_FROM}`
    
    # loop over all the databases
    for DATABASE in $DATABASES; do
    # skip non-databases
    if [ "${DATABASE}" != "Database" ] && [ "${DATABASE}" != "information_schema" ]; then
    echo "transmitting ${DATABASE}"
    
    # create database on remote (receiving) side if it doesn't exist
    echo "CREATE DATABASE IF NOT EXISTS ${DATABASE}" | ${CMD_MYSQL} -p${DB_PASS_TO} -u ${DB_USER_TO} -h ${DB_HOST_TO}
    
    # dump the current database and pipe it directly to the remote (receiving) side to inject it
    ${CMD_MYSQLDUMP} -Q -B --create-options --delayed-insert --complete-insert --quote-names --add-drop-table -p${DB_PASS_FROM} -u${DB_USER_FROM} -h${DB_HOST_FROM} ${DATABASE} | ${CMD_MYSQL} -p${DB_PASS_TO} -u ${DB_USER_TO} -h ${DB_HOST_TO} ${DATABASE}
    fi
    done
     
    Last edited: Feb 18, 2015

Share This Page