Skip to content

Instantly share code, notes, and snippets.

@yvh
Last active May 15, 2017 15:33
Show Gist options
  • Save yvh/1ac35367644c7f4e041a to your computer and use it in GitHub Desktop.
Save yvh/1ac35367644c7f4e041a to your computer and use it in GitHub Desktop.
MySQL dump script
#!/usr/bin/env bash
# Author Yannick Vanhaeren
# Version 1.0
set -o errexit
set -o pipefail
set -o nounset
# set -o xtrace
function usage
{
echo "usage: mysql-backup [-H hostname] [-P port] [-u user] [-p password] [-F defaults-file] [-D destination] [-h] database"
}
MYSQLDUMP="$(which mysqldump)"
HOST="127.0.0.1"
PORT="3306"
DATABASE=""
USER="root"
PASSWD=""
DEFAULTS_FILE=""
DESTINATION="."
while getopts "H:P:u:p:F:D:kh" opt; do
case $opt in
H)
HOST=$OPTARG
;;
P)
PORT=$OPTARG
;;
u)
USER=$OPTARG
;;
p)
PASSWD=$OPTARG
;;
F)
DEFAULTS_FILE=$OPTARG
;;
D)
DESTINATION=$OPTARG
;;
h)
usage
exit
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
shift $((OPTIND-1)) # remove parsed options and args from $@ list
DATABASE=$1
if [ -z "$DATABASE" ]; then
echo -e "\033[0;31mYou must specify a database name\033[0m"
exit 1
fi
if [ -n "$DEFAULTS_FILE" ]; then
DEFAULTS_FILE='--defaults-file='$DEFAULTS_FILE
fi
FILE="${DATABASE}_$(date +"%Y-%m-%d_%H-%M-%S").sql.gz"
echo -e "\033[0;32mDumping and Compressing\033[0m"
$MYSQLDUMP $DEFAULTS_FILE -h$HOST -P$PORT -u$USER -p$PASSWD -v $DATABASE | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' | gzip -9 > "${DESTINATION}/${FILE}"
echo -e "\033[0;32m\nDone!\033[0m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment