Skip to content

Instantly share code, notes, and snippets.

@ibejohn818
Last active May 2, 2017 18:01
Show Gist options
  • Save ibejohn818/7cf13b681e805afdb49dfc6bd61f89c6 to your computer and use it in GitHub Desktop.
Save ibejohn818/7cf13b681e805afdb49dfc6bd61f89c6 to your computer and use it in GitHub Desktop.
MySQL Dump & Import between two databases a single table at a time
#!/usr/bin/env bash
###EXAMPLE USAGE
#./mysql-dump-import-table.sh {OUTHOST:OPTIONAL-PORT} {OUTUSER} {OUTDB_NAME} {INHOST:OPTIONAL-PORT} {INUSER} {INDB_NAME}
#Export Vars
DB_host=$1
DB_user=$2
DB=$3
#import vars
IDB_host=$4
IDB_user=$5
IDB=$6
#try to explode DB_host to check for port
PORTCHK=(${DB_host//:/ })
if test "${PORTCHK[1]+isset}"; then DB_port=${PORTCHK[1]}; else DB_port=3306; fi;
#same port check for IDB_host
IPORTCHK=(${IDB_host//:/ })
if test "${IPORTCHK[1]+isset}"; then IDB_port=${IPORTCHK[1]}; else IDB_port=3306; fi;
echo -n "Staging Path: "
read DIR
echo -n "Export DB password: "
read -s DB_pass
echo
echo -n "Import DB Password: "
read -s INDB_pass
echo
echo "Export Vars:"
echo -e "\t Host: $DB_host"
echo -e "\t User: $DB_user"
echo -e "\t DB: $DB"
echo -e "\t Port: $DB_port"
echo "Import Vars:"
echo -e "\t Host: $IDB_host"
echo -e "\t User: $IDB_user"
echo -e "\t DB: $IDB"
echo -e "\t Port: $IDB_port"
[ -n "$DIR" ] || DIR=.
test -d $DIR || mkdir -p $DIR
echo "Staging table dump from database: '$DB'; into dir=$DIR"
tbl_count=0
for t in $(mysql --skip-secure-auth -NBA -h $DB_host -P $DB_port -u $DB_user -p$DB_pass -D $DB -e 'show tables')
do
echo "DUMPING TABLE: $DB.$t"
mysqldump --skip-secure-auth --hex-blob --add-drop-table --single-transaction -h $DB_host -P $DB_port -u $DB_user -p$DB_pass $DB $t | gzip > $DIR/$DB.$t.sql.gz
echo "IMPORTING TABLE: $DB.$t"
gunzip < $DIR/$DB.$t.sql.gz | mysql --max_allowed_packet=512M --skip-secure-auth -h $IDB_host -P $IDB_port -u $IDB_user -p$INDB_pass -D $IDB
tbl_count=$(( tbl_count + 1 ))
done
echo "$tbl_count tables imported from '$DB_host':'$DB' to '$IDB_host':'$IDB'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment