Last active
August 29, 2015 14:03
-
-
Save amirkdv/c7d508f4a5d59576b1cf to your computer and use it in GitHub Desktop.
Cleanly run commands that require mysql running
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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