Skip to content

Instantly share code, notes, and snippets.

@amirkdv amirkdv/mysqldo.sh
Last active Aug 29, 2015

Embed
What would you like to do?
Cleanly run commands that require mysql running
#!/bin/bash
# Executes the provided arguments as a shell command with a twist: if mysql is
# not already running: starts mysql, runs the commands, and stops mysql.
# Example usage:
# - mysqldo mysql -u root -p # will open an interactive shell and will stop mysql
# # when you leave the shell
# - mysqldo 'echo "show databases;" | mysql -u root -p"my_password"'
# # note that if your commands involve pipes or anything that the shell
# # interpretter would not pass to mysqldo as arguments, you should wrap the
# # entire command in quotes.
already_running=
pid_file=/var/run/mysqld/mysqld.pid
stat=0
log() { echo -e "\033[0;33m[mysqldo] $1\033[00m" >&2; }
get_pid(){ [[ -e $pid_file ]] && cat $pid_file; }
main(){
# start mysql if necessary
if [[ -e $pid_file ]]; then
log 'mysql already running'
already_running=1
else
log 'starting mysql'
mysqld_safe --skip-syslog >/dev/null 2>&1 &
until [ -n "$(get_pid)" ]; do sleep 0.5; done
fi
log "$@"
eval "$@"
stat=$?
}
# stop mysql if it was not already running
clean(){
[[ -n $already_running ]] && return
log 'stopping mysql'
get_pid | xargs kill
until [[ -z $(get_pid) ]]; do sleep 0.5; done
}
trap clean SIGINT SIGKILL SIGTERM
main "$@"
clean
exit $stat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.