Skip to content

Instantly share code, notes, and snippets.

@mdeeks
Created November 13, 2013 22:57
Show Gist options
  • Save mdeeks/7458042 to your computer and use it in GitHub Desktop.
Save mdeeks/7458042 to your computer and use it in GitHub Desktop.
Generic bash init script. Should work on both OS X and *nix. Probably won't support apps that fork. Works great for daemonizing things like python or ruby scripts.
#!/bin/bash
BasePath="$(cd $(dirname "${BASH_SOURCE[0]}")/.. && pwd)" # Absolute path. Will be CWD when run.
AppName="SomeApp"
Command="$BasePath/bin/your_script.sh"
LogFile="$BasePath/logs/run.log"
PidFile="$BasePath/pid"
ReloadSignal="USR1" # Leave this blank if your app doesn't support reloading
StopTimeout=10 # Max seconds to wait for process to terminate
# ------
isRunning() {
pid="$(cat $PidFile 2> /dev/null )"
if [[ $? == "0" && ! -z "$pid" ]]; then
ps $pid > /dev/null
return $?
fi
return 1
}
doStart() {
if isRunning; then
echo "$AppName is already running"
else
echo "Starting $AppName..."
cd $BasePath &&
exec $Command > $LogFile 2>&1 <&- &
# This is here as a total hack. Bash doesn't actually wait for a background process to launch.
# So sometimes $! will be empty. Waiting a second "solves" that.
sleep 1
pid=$!
echo "$pid" > $PidFile
fi
}
doStop() {
if isRunning; then
pid=$(cat "$PidFile")
echo -n "Stopping $AppName..."
kill $pid
sleep 1
while isRunning; do
timer=$(($timer + 1))
if [[ $timer -ge $StopTimeout ]]; then
break;
fi
sleep 1
echo -n "."
done
echo
if isRunning; then
echo "Unable to stop process" >&2
exit 1
fi
rm $PidFile
else
echo "$AppName is not running"
fi
}
doStatus() {
if isRunning; then
echo "$AppName is running: $(cat $PidFile)"
else
echo "$AppName is not running"
return 3
fi
}
doReload() {
if isRunning; then
if [[ $ReloadSignal != "" ]]; then
kill -s $ReloadSignal $(cat $PidFile)
else
echo "Reload is not supported"
fi
else
echo "$AppName is not running"
return 3
fi
}
case "$1" in
start)
doStart
;;
stop)
doStop
;;
restart)
doStop
doStart
;;
status)
doStatus
;;
reload)
doReload
;;
*)
echo "Command must be one of: start, stop, restart, status, reload"
exit 1
;;
esac
@mdeeks
Copy link
Author

mdeeks commented Nov 13, 2013

TODO: add support for running command as another user. Should probably add force-reload and try-restart too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment