Skip to content

Instantly share code, notes, and snippets.

@claudiobastos
Created March 9, 2018 11:44
Show Gist options
  • Select an option

  • Save claudiobastos/ed0e407926b80c3b01d56af46fa03872 to your computer and use it in GitHub Desktop.

Select an option

Save claudiobastos/ed0e407926b80c3b01d56af46fa03872 to your computer and use it in GitHub Desktop.
#!/bin/bash
# dump-tables-mysql.sh
# Descr: Dump MySQL table data into separate SQL files for a specified database.
# Usage: Run without args for usage info.
# Author: @Trutane
# Ref: http://stackoverflow.com/q/3669121/138325
# Notes:
# * Script will prompt for password for db access.
# * Output files are compressed and saved in the current working dir, unless DIR is
# specified on command-line.
[ $# -lt 3 ] && echo "Usage: $(basename $0) <DB_HOST> <DB_USER> <DB_NAME> [<DIR>]" && exit 1
DB_host=$1
DB_user=$2
DB=$3
DIR=$4
[ -n "$DIR" ] || DIR=.
test -d $DIR || mkdir -p $DIR
echo -n "DB password: "
read -s DB_pass
echo
echo "Dumping tables into separate SQL command files for database '$DB' into dir=$DIR"
tbl_count=0
for t in $(mysql -NBA -h $DB_host -u $DB_user -p$DB_pass -D $DB -e 'show tables')
do
echo "DUMPING TABLE: $DB.$t"
mysqldump -h $DB_host -u $DB_user -p$DB_pass $DB $t | gzip > $DIR/$DB.$t.sql.gz
tbl_count=$(( tbl_count + 1 ))
done
#!/bin/bash
# restore tables mysql
# Descr: Restore MySQL tables data to a Database from a list of files in a directory.
# Usage: Run without args for usage info.
# Author: @claudiobastos based on @Trutane dump tables script
# Based on: http://stackoverflow.com/q/3669121/138325
# Notes:
# * Script will prompt for password for db access.
# * use gzip -d * before try this script
# * Input files are compressed and saved in the current working dir.
[ $# -lt 3 ] && echo "Usage: $(basename $0) <DB_HOST> <DB_USER> <DB_NAME> [<DIR>]" && exit 1
DB_host=$1
DB_user=$2
DB=$3
DIR=$4
[ -n "$DIR" ] || DIR=.
test -d $DIR || cd $DIR
echo -n "DB password: "
read -s DB_pass
echo
echo "Restorgin SQL command files into database '$DB' from dir=$DIR"
tbl_count=0
for t in *.sql
do
echo "Restoring file: $t"
mysql -h $DB_host -u $DB_user -p$DB_pass $DB < $t
tbl_count=$(( tbl_count + 1 ))
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment