Skip to content

Instantly share code, notes, and snippets.

@al-v-in
Last active May 9, 2022 01:42
Show Gist options
  • Save al-v-in/9347293 to your computer and use it in GitHub Desktop.
Save al-v-in/9347293 to your computer and use it in GitHub Desktop.
Convenience script to quickly import and dump mysql databases
#!/bin/bash
#
#
# maybe you'll want to have another script that calls this one, which
# holds the credentials, it would look like:
#
# ./dbio.sh -m $1 -u user -p pass -d dbname -w "../db/whole.sql" -s "../db/schema.sql" -b "../tmp/mysql-backups/"
#
# where the argument to that script is "dump" or "import"
#
set -e #stop script on error
usage()
{
cat << EOF
REQUIRED OPTIONS:
-m Mode: "dump" or "import"
-u Username
-p Password
-d Database name
OPTIONAL OPTIONS:
-h Show this message
-w File path to whole sql output
-s File path to schema sql output
-b Directory path to sql backup dir
EOF
}
# Varibles init
USER=""
PWD=""
DBNAME=""
MODE=""
DBDUMPWHOLEFILEPATH="dbwhole.sql"
DBDUMPSCHEMAFILEPATH="dbschema.sql"
DBBACKUPDIRPATH="dbbackups/"
# Get arguments
while getopts hm:u:p:d:w:s:b: opts; do
case ${opts} in
h) usage
exit 1 ;;
m) MODE=${OPTARG} ;;
u) USER=${OPTARG} ;;
p) PWD=${OPTARG} ;;
d) DBNAME=${OPTARG} ;;
w) DBDUMPWHOLEFILEPATH=${OPTARG} ;;
s) DBDUMPSCHEMAFILEPATH=${OPTARG} ;;
b) DBBACKUPDIRPATH=${OPTARG} ;;
esac
done
if [[ -z $MODE ]] || [[ -z $USER ]] || [[ -z $PWD ]] || [[ -z $DBNAME ]]
then
usage
exit 1
fi
if [ "$MODE" == "import" ]
then
NOW=$(date +"%Y-%m-%d-%T")
DBBACKUPFILEPATH=$DBBACKUPDIRPATH"dbbackup.$NOW.sql"
echo "Making backup of current database"
mysqldump -v --compact --routines -u $USER -p$PWD --default-character-set=utf8 $DBNAME > $DBBACKUPFILEPATH
echo "Dropping DB"
mysql -u$USER -p$PWD -h localhost -e "DROP DATABASE $DBNAME"
echo "Creating new DB"
mysql -u$USER -p$PWD -h localhost -e "CREATE DATABASE $DBNAME"
# :: IMPORT DATABASE
echo "Importing DB content"
mysql -u$USER -p$PWD --default-character-set=utf8 -h localhost $DBNAME < $DBDUMPWHOLEFILEPATH
elif [ "$MODE" == "dump" ]
then
echo "Dumping whole DB to $DBDUMPWHOLEFILEPATH"
mysqldump -v --compact --routines --complete-insert -u $USER -p$PWD --default-character-set=utf8 $DBNAME > $DBDUMPWHOLEFILEPATH
echo "Dumping DB schema to $DBDUMPSCHEMAFILEPATH"
mysqldump -v --no-data --routines --complete-insert -u $USER -p$PWD --default-character-set=utf8 $DBNAME > $DBDUMPSCHEMAFILEPATH
else
echo "Error: -m must be 'dump' or 'import'"
fi
@Longwater1234
Copy link

thanks for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment