Service command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search

The service command is used to run a System V init script. Usually all system V init scripts are stored in /etc/init.d directory and service command can be used to start, stop, and restart the daemons and other services under Linux. All scripts in /etc/init.d accepts and supports at least the start, stop, and restart commands.

Syntax

The general syntax is as follows:

service SCRIPT-Name COMMAND

The COMMAND can be at least start, stop, status, and restart.

The stop command

The syntax is as follows:

service SCRIPT-Name stop

To stop the sshd service, enter:

service sshd stop

The start command

The syntax is as follows:

service SCRIPT-Name start

To start the sshd service, enter:

service sshd start

The status command

The syntax is as follows:

service SCRIPT-Name status

To get current status of the sshd service, enter:

service sshd status

The restart command

The syntax is as follows:

service SCRIPT-Name restart

To restart the sshd service, enter:

service sshd restart

How do I write my own System V init script?

The general syntax is as follows:

#!/bin/bash
#
# lighttpd     Startup script for the lighttpd server 
#
# chkconfig: - 85 15
# description: Lighttpd web server
#
# processname: lighttpd
 
# Source function library.
. /etc/rc.d/init.d/functions
 
conf="/etc/lighttpd/lighttpd.conf"
prog=lighttpd
lighttpd="/usr/sbin/lighttpd"
pidfile="/var/run/lighttpd.pid"
user="lighttpd"
 
# get custome config
if [ -f /etc/sysconfig/lighttpd ]; then
        . /etc/sysconfig/lighttpd
fi
 
 
start(){
}
 
stop(){
}
 
reload(){
}
 
status(){
}
 
case "$1" in
        start)
                start 
                ;;
        stop)
                stop 
                ;;
        restart)
                stop
                start
                ;;
        reload)
                reload
		;;
        status)
                status
                ;;
        *)
                echo $"Usage: $0 {start|stop|restart|reload|status}" 
esac

You need to write actual code start(), stop(), and other functions. The following start() can be used as follows to start lighttpd server:

# start lighttpd web server
start(){
	echo -n "Starting "
        $lighttpd -f $conf 
	[ $? -eq 0 ] && echo " [ OK ] " || echo " [ FAILED ] "
}
 
# stop lighttpd web server
stop(){
        echo -n $"Stopping $prog "
        [ -f "$pidfile" ] && read line < "$pidfile"
        if [ -d "/proc/$line" -a -f $conf ]
        then
  	      pkill -KILL -u $user $prog
              [ $? -eq 0 ] && echo " [ OK ] " || echo " [ FAILED ] "
              [ -f "$pidfile" ] && rm -f "$pidfile"
	fi
}

See also