Skip to content

Instantly share code, notes, and snippets.

@ampedandwired
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ampedandwired/b7dc821cb09456f99c41 to your computer and use it in GitHub Desktop.
Save ampedandwired/b7dc821cb09456f99c41 to your computer and use it in GitHub Desktop.
Generic sysv init
#!/bin/bash
service_name=`basename $0`
# Load default variables. Provides a way to configure the service
# differently in different environments.
if [ -f /etc/default/${service_name} ]; then
source /etc/default/${service_name}
fi
# -----------------------------------------------------------------------------
# The following are configurable options that can be changed locally by
# setting them in /etc/default/$service_name
# The path to the service script
progpath=${progpath:-'/usr/local/bin/yourscript.sh'}
# Who to run the sync as. This user should be able to ssh passwordless to
# the destination machine
runas=${runas:-'root'}
# arguments to script
opts=${opts:-''}
# -----------------------------------------------------------------------------
# Should not need to change anything below here
# binary program name
prog=$(basename $progpath)
# program name without extension
prog_name="${prog%.*}"
# pid file
pidfile="/var/run/${prog_name}.pid"
# log file for program
logdir=/var/log/${prog_name}
logfile=${logdir}/${prog_name}.log
mkdir -p $logdir
chown -R $runas $logdir
# make sure full path to executable binary is found
! [ -x $progpath ] && echo "$progpath: executable not found" && exit 1
eval_cmd() {
local rc=$1
if [ $rc -eq 0 ]; then
echo '[ OK ]'
else
echo '[FAILED]'
fi
return $rc
}
start() {
# see if running
local pids=$(pidof -x $prog)
if [ -n "$pids" ]; then
echo "$prog (pid $pids) is already running"
return 0
fi
printf "%-50s%s" "Starting $prog: " ''
su - $runas -c "$progpath $opts" &> ${logfile} &
# save pid to file
echo $! > $pidfile
# check again if running
sleep 1
pidof -x $prog >/dev/null 2>&1
eval_cmd $?
}
stop() {
# see if running
local pids=$(pidof -x $prog)
if [ -z "$pids" ]; then
echo "$prog not running"
return 0
fi
printf "%-50s%s" "Stopping $prog: " ''
rm -f $pidfile
kill -9 $pids
eval_cmd $?
}
status() {
# see if running
local pids=$(pidof -x $prog)
if [ -n "$pids" ]; then
echo "$prog (pid $pids) is running"
else
echo "$prog is stopped"
fi
}
case $1 in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
stop
sleep 1
start
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
exit 1
esac
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment