Skip to content

Instantly share code, notes, and snippets.

@sebble
Created July 5, 2013 09:34
Show Gist options
  • Save sebble/5933319 to your computer and use it in GitHub Desktop.
Save sebble/5933319 to your computer and use it in GitHub Desktop.
A script to run any executable in background, check if it is already running, or kill the process tree (includes children spawned from main executable).
#!/bin/bash
# simple service checker, starter, process tree killer
# usage:
# init.sh <script_path> [start|stop|status|restart]
SCRIPT=$1
ACTION=$2
BASENAME=$(basename $SCRIPT)
NAME=$BASENAME
GROUPPID=$(ps x -o "%r %c" | grep -v grep | grep -v init | grep $BASENAME | awk '{print "-" $1}')
RUNNING="$(ps aux | grep -v grep | grep -v cron/init | grep -c $BASENAME)"
STOP="kill -TERM $GROUPPID"
## uncommment this for logging
#LOGFILE="/var/log/initsh/$(basename $SCRIPT).log"
#ERRFILE="/var/log/initsh/$(basename $SCRIPT).err"
#mkdir -p /var/log/initsh
## commment this for logging
LOGFILE="/dev/null"
ERRFILE="/dev/null"
case "$ACTION" in
"start")
if [ "$RUNNING" -eq "0" ]; then
echo "Init: Starting $NAME"
$SCRIPT 1>> $LOGFILE 2>> $ERRFILE &
else
echo "Init: $NAME is running"
fi
;;
"stop")
if [ "$RUNNING" -eq "0" ]; then
echo "Init: $NAME is NOT running";
else
echo "Init: Stopping $NAME"
$STOP
fi
;;
"status")
if [ "$RUNNING" -eq "0" ]; then
echo "Init: $NAME is NOT running";
else
echo "Init: $NAME is running"
fi
;;
"restart")
if [ "$RUNNING" -eq "0" ]; then
echo "Init: Starting $NAME"
$SCRIPT 1>> $LOGFILE 2>> $ERRFILE &
else
echo "Init: Stopping $NAME"
$STOP
echo "Init: Starting $NAME"
$SCRIPT 1>> $LOGFILE 2>> $ERRFILE &
fi
;;
*)
# do nothing (help)
echo "usage:"
echo " $0 <script_path> [start|stop|status|restart]"
;;
esac
@sebble
Copy link
Author

sebble commented Jul 5, 2013

To do:

  • add executable check
  • add confirmation of successful start check ($? and 'status')
  • add option for log directory location?

@sebble
Copy link
Author

sebble commented Jul 5, 2013

Notes:

  • cannot use $? for backgrounded process
  • should use pidof -x $BASENAME to check status?

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