LSB Init.d Script Template

Managing daemons on Linux

Quick little init.d template:

#!/bin/bash
# <Application Name>
# chkconfig: 345 20 80
# description: <Description>
# processname: <Process Name|Application Name|Short name>
# author: Richard Sumilang <me@richardsumilang.com>
# see: https://wiki.debian.org/LSBInitScripts


CMD=""                             # Command goes here
NAME="<Short Application Name>"    # Short Application Name
PIDFILE=/var/run/$NAME.pid         # Process ID File
SCRIPTNAME=/etc/init.d/$NAME       # This script name

case "$1" in
start)

    # Make sure process is not already running
    if [ -f $PIDFILE ]; then
        echo "PID already exists: $PIDFILE"
        exit 1
    fi

    # Use pgrep to retrieve the Process ID
    $CMD
    sleep 1
    PID=`pgrep -fn "$CMD"`

    # Save process ID to file
    if [ -z $PID ]; then
        printf "%s\n" "Failed to start $NAME"
    else
        echo $PID > $PIDFILE
        printf "%s\n" "$NAME ... Ok"
    fi
;;
status)
    printf "%-50s" "Checking $NAME..."
    if [ -f $PIDFILE ]; then
        PID=`cat $PIDFILE`
        if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then
            printf "%s\n" "Process dead but pidfile exists"
        else
            echo "$NAME is Running"
        fi
    else
        printf "%s\n" "$NAME is not running"
    fi
;;
stop)
    printf "%-50s" "Stopping $NAME"
    PID=`cat $PIDFILE`
    if [ -f $PIDFILE ]; then
        kill $PID
        printf "%s\n" "Ok"
        rm -f $PIDFILE
    else
        printf "%s\n" "pidfile not found"
    fi
;;

restart)
    $0 stop
    $0 start
;;

*)
    echo "Usage: $0 {status|start|stop|restart}"
    exit 1
esac
Jul 7, 2014 Servers

Support this blog

Buy yourself ANYTHING!

That's right! Shop as you normally would using Amazon.com with my affiliate link and the commissions made go directly into keeping this blog healthy. It's that simple! The hardware and software costs used for this site comes out of my own pocket and it's expensive. Lets keep this site ad free :)

Start shopping on Amazon.com now!

Thank you!
Richard S.