Skip to content

Instantly share code, notes, and snippets.

@juliangut
Created April 6, 2016 15:11
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 juliangut/ee91e51444e82efb5d5020576e69f13f to your computer and use it in GitHub Desktop.
Save juliangut/ee91e51444e82efb5d5020576e69f13f to your computer and use it in GitHub Desktop.
init.d service template
#!/bin/bash
### BEGIN INIT INFO
# Provides:
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: Enable service provided by daemon.
### END INIT INFO
NAME="service_name"
CMD_PATH="path_to_command"
CMD="command"
PID_FILE="/var/run/$NAME.pid"
LOG_PATH="/var/log/project_folder"
STDOUT_FILE="$LOG_PATH/$NAME.log"
STDERR_FILE="$LOG_PATH/${NAME}_err.log"
get_pid() {
if [ -f "$PID_FILE" ]; then
cat "$PID_FILE"
else
echo ""
fi
}
is_running() {
[ -f "$PID_FILE" ] && ps `get_pid` > /dev/null 2>&1
}
case "$1" in
start)
printf "%-50s" "Starting $NAME..."
if is_running; then
PID=`get_pid`
printf "%s\n" "Already running, process $PID"
else
if [ ! -d "$LOG_PATH" ]; then
mkdir $LOG_PATH
fi
PID=`$CMD_PATH/$CMD >> $STDOUT_FILE 2>> $STDERR_FILE & echo $!`
if [ -z $PID ] || ! ps $PID > /dev/null 2>&1; then
printf "%s\n" "Failed"
else
echo $PID > $PID_FILE
printf "%s\n" "Running, process $PID"
fi
fi
;;
stop)
printf "%-50s" "Stopping $NAME..."
if ! is_running; then
printf "%s\n" "Already stopped"
else
kill -HUP `get_pid`
if is_running; then
printf "%s\n" "Failed, process ${get_pid}"
exit 1
else
if [ -f "$PID_FILE" ]; then
rm -f $PID_FILE
fi
printf "%s\n" "Stopped"
fi
fi
;;
restart)
if is_running; then
$0 stop
if is_running; then
printf "%s\n" "Stopping service failed, skipping start"
exit 1
fi
fi
$0 start
;;
status)
printf "%-50s" "Checking $NAME..."
PID=`get_pid`
if is_running; then
printf "%s\n" "Running, process $PID"
elif ! ps $PID > /dev/null 2>&1; then
printf "%s\n" "Process dead but pidfile exists"
else
printf "%s\n" "Stopped"
fi
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment