I'm working with a Rails app that requires a few layers of infrastructure to run: MySQL, Redis, Sidekiq, and (of course) the Rails server. I wrote some functions to help me manage the various servers (start/stop/check and one to kill the rails server when it gets hung up and decides to eat all my memory rather than shutting down).
I'm still new to Bash scripting, and looking for all the feedback/criticism I can get, so please, don't hold back. I'm particularly interested in how I can further DRY up this code.
Generic helpers to check if a named process is running and get its pid:
function running {
pgrep -f "$1" &> /dev/null
}
function rpid {
pgrep -f "$1" 2> /dev/null
}
MySQL server:
function msta {
if ! running mysql; then
mysql.server start
else
echo "MySQL already running"
fi
}
function msto {
if running mysql; then
mysql.server stop
else
echo "MySQL not running"
fi
}
function mstat {
if running mysql; then
echo "MySQL running"
else
echo "MySQL not running"
fi
}
Redis server:
function resta {
if ! running redis; then
redis-server ~/.redis/redis.conf
until running redis; do
sleep 1
done
echo "Redis daemon started"
else
echo "Redis daemon already running"
fi
}
function resto {
if running redis; then
kill $(rpid redis)
while running redis; do
sleep 1
done
echo "Redis daemon stopped"
else
echo "Redis daemon not running"
fi
}
function restat {
if running redis; then
echo "Redis daemon running"
else
echo "Redis daemon not running"
fi
}
Sidekiq:
function sksta {
if ! running sidekiq; then
sidekiq -d
until running sidekiq; do
sleep 1
done
echo "Sidekiq daemon started"
else
echo "Sidekiq daemon already running"
fi
}
function sksto {
if running sidekiq; then
kill $(rpid sidekiq)
while running sidekiq; do
sleep 1
done
echo "Sidekiq daemon stopped"
else
echo "Sidekiq daemon not running"
fi
}
function skstat {
if running sidekiq; then
echo "Sidekiq daemon running"
else
echo "Sidekiq daemon not running"
fi
}
Rails server:
# kill the Rails server
function krs {
if running 'rails s'; then
kill $1 $(rpid 'rails s')
for i in 1 2; do
if ! running 'rails s'; then
break
else
sleep 1
fi
done
reportkill
else
echo "Rails server not running"
fi
}
function reportkill {
if ! running 'rails s'; then
echo "Rails server killed"
else
echo "Rails server survived (pid $(rpid 'rails s'))"
fi
}
# when a `kill -9` is required
function krs9 {
krs '-9'
}
function rastat {
if running 'rails s'; then
echo "Rails server running"
else
echo "Rails server not running"
fi
}
MySQL + Redis + Sidekiq
function asta {
msta && resta && sksta
}
function asto {
sksto && resto && msto
}
function astat {
mstat && restat && skstat
}