Skip to content

Instantly share code, notes, and snippets.

@xperjon
Created December 3, 2020 13:40
Show Gist options
  • Save xperjon/95cdd8226acf5255369dbd65b45d1194 to your computer and use it in GitHub Desktop.
Save xperjon/95cdd8226acf5255369dbd65b45d1194 to your computer and use it in GitHub Desktop.
Run mysqldump in Docker container
#!/usr/bin/env bash
cmdname=$(basename $0)
[[ -x "$(command -v docker)" ]] || { echo "This script requires docker to be installed" >&2; exit 1; }
usage () {
cat <<END
Usage:
$cmdname [OPTIONS] db [args to mysqldump]
Dump database to local file SQL script.
The dump will contain both schema and data. This can be overwritten by
passing additional arguments to mysqldump, e.g. --no-create-info or --no-data
For complete argument list visit: https://dev.mysql.com/doc/refman/8.0/en/mysqldump.html
Parameters
db : The name of the database to dump.
Options
-h : Host. Defaults to env variable MYSQL_HOST.
-P : Port. Defaults to env variable MYSQL_PORT.
-u : Username. Defaults to env variable MYSQL_USERNAME.
-p : Password. Default to env varible MYSQL_PASSWORD.
-o : Output file (will be overwritten). Defaults to ./db.sql.
END
}
spin()
{
spinner="/|\\-/|\\-"
while :
do
for i in `seq 0 7`
do
echo -n "${spinner:$i:1}"
echo -en "\010"
sleep 0.1
done
done
}
declare user=${MYSQL_USERNAME}
declare pwd=${MYSQL_PASSWORD}
declare host=${MYSQL_HOST}
declare port=${MYSQL_PORT}
while getopts "h:P:u:p:o:" opt; do
case $opt in
h)
host=${OPTARG}
;;
P)
port=${OPTARG}
;;
u)
user=${OPTARG}
;;
p)
pwd=${OPTARG}
;;
o)
outfile=${OPTARG}
;;
\?)
exit 1
;;
esac
done
shift $(( OPTIND -1))
[[ $1 ]] || { echo "missing db parameter" && usage; >&2 exit 1; }
[[ $user ]] || { echo "no user found" && usage; >&2 exit 1; }
[[ $pwd ]] || { echo "no password found" && usage; >&2 exit 1; }
[[ $host ]] || { echo "no host found" && usage; >&2 exit 1; }
[[ $port ]] || { echo "no port found" && usage; >&2 exit 1; }
declare db=$1
shift
dumpargs=$@
[[ $outfile ]] || outfile=${db}.sql
#TODO: check write permission on outfile
echo "Start dumping..."
# Start the Spinner:
spin &
# Make a note of its Process ID (PID):
SPIN_PID=$!
# Kill the spinner on any signal, including our own exit.
trap "kill -9 $SPIN_PID" `seq 0 15`
docker run --rm -it mariadb:10.4.2-bionic mysqldump \
-h "$host" \
-P "$port" \
-u "$user" \
-p"$pwd" \
"$db" \
$dumpargs > $outfile
#Check if success
if [[ $? -ne 0 ]]; then
#error msg will be in tempfile
cat "${outfile}" && rm "${outfile}"
exit 1
fi
echo "Finished."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment