Skip to content

Instantly share code, notes, and snippets.

@hbin
Forked from naholyr/_service.md
Created October 26, 2017 02:34
Show Gist options
  • Select an option

  • Save hbin/cf018b7845d89612212ed8efef3fb37f to your computer and use it in GitHub Desktop.

Select an option

Save hbin/cf018b7845d89612212ed8efef3fb37f to your computer and use it in GitHub Desktop.
Sample /etc/init.d script

Sample service script for debianoids

Look at LSB init scripts for more information.

Usage

Copy to /etc/init.d:

# replace "$YOUR_SERVICE_NAME" with your service's name (whenever it's not enough obvious)
cp "service.sh" "/etc/init.d/$YOUR_SERVICE_NAME"
chmod +x /etc/init.d/$YOUR_SERVICE_NAME

Edit the script and replace following tokens:

  • <NAME> = $YOUR_SERVICE_NAME
  • <DESCRIPTION> = Describe your service here (be concise)
  • Feel free to modify the LSB header, I've made default choices you may not agree with
  • <COMMAND> = Command to start your server (for example /home/myuser/.dropbox-dist/dropboxd)
  • <USER> = Login of the system user the script should be run as (for example myuser)

Start and test your service:

service $YOUR_SERVICE_NAME start
service $YOUR_SERVICE_NAME stop

Install service to be run at boot-time:

update-rc.d $YOUR_SERVICE_NAME defaults

Enjoy

I'm noob and/or lazy

Yep, I'm lazy too.

I may edit the gist and provide an automated way to install new services.

#!/bin/sh
### BEGIN INIT INFO
# Provides: <NAME>
# Required-Start: $local_fs $network $named $time $syslog
# Required-Stop: $local_fs $network $named $time $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: <DESCRIPTION>
### END INIT INFO
SCRIPT=<COMMAND>
RUNAS=<USER>
PIDNAME=$(basename "$0")
start() {
if [ -f /var/run/$PIDNAME ] && kill -0 $(cat /var/run/$PIDNAME); then
echo 'Service already running' >&2
exit 1
fi
echo 'Starting service…' >&2
local CMD="$SCRIPT &> /dev/stderr & echo \$!"
su -c "$CMD" $RUNAS > /var/run/$PIDNAME
echo 'Service started' >&2
}
stop() {
if [ ! -f /var/run/$PIDNAME ] || ! kill -0 $(cat /var/run/$PIDNAME); then
echo 'Service not running' >&2
exit 1
fi
echo 'Stopping service…' >&2
kill -15 $(cat /var/run/$PIDNAME) && rm -f /var/run/$PIDNAME
echo 'Service stopped' >&2
}
case "$1" in
start)
start
;;
stop)
stop
;;
retart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment