Thursday, March 17, 2011

Bash functions to dump and load a mysql database

Everyone probably has one of these, but here is mine. It's a bit rough but works for me. If I was going to make it better I'd probably use getopt instead of $1 and $2 and then add options for changing the mysql user. (Currently it hard codes the user as root). Put it in your .bash_aliases or .bashrc or wherever you keep these types of things.
# Dump a mysql database to a gzipped sql file
dbdump() {
# (adjust defaults as required)
GZ_FILE=$1; [ ! -n "$GZ_FILE" ] && GZ_FILE="$HOME/.dbdump.gz"
DB_NAME=$2; [ ! -n "$DB_NAME" ] && DB_NAME='fms'
echo -n "Dumping database $DB_NAME to $GZ_FILE..."
# Add --extended-insert=FALSE to mysql command for more readable but MUCH slower sql
mysqldump -u root $DB_NAME | gzip - > "$GZ_FILE"
echo ' Done'
}
# Load a mysql database from a gzipped sql file
dbload() {
# (adjust defaults as required)
GZ_FILE=$1; [ ! -n "$GZ_FILE" ] && GZ_FILE="$HOME/.dbdump.gz"
DB_NAME=$2; [ ! -n "$DB_NAME" ] && DB_NAME='fms'
echo -n "Loading database $DB_NAME from $GZ_FILE..."
echo "DROP DATABASE $DB_NAME; CREATE DATABASE $DB_NAME;" | mysql -u root
zcat $GZ_FILE | mysql -u root -D $DB_NAME
echo ' Done'
}
view raw dbdump.sh hosted with ❤ by GitHub
Update: I made a set of rake tasks for doing this kind of thing, so I'm not actually using this any more.

No comments: