Tille - I can see you, read those man pages!   Tille's Site

A real world case statement

The directory containing the init scripts for your Unix or Linux system, usually /etc/init.d or /etc/rc.d/init.d or something similar, is full of scripts that use case statements.

The possible cases are usually start, stop, restart and such. Let's look at one of those scripts, named anacron after the anacron daemon it manages.

(Anacronworks like any other cron, except that it does not expect or assume your machine to be running continuously.

#!/bin/sh
# Startup script for anacron
#
# chkconfig: 2345 95 05
# description: Run cron jobs that were left out due to downtime

# Source function library.
# This library contains functions not defined in this script, such as 'daemon'.

. /etc/rc.d/init.d/functions

# See if we exist:

[ -f /usr/sbin/anacron ] || exit 0

# So as not to confuse ourselves.

prog="anacron"

# Definition of the start function

start() {

# Mind the difference in use: $prog is just a name, anacron is the actual 
# executable (do which anacron, that's the one).

    echo -n $"Starting $prog: "
    daemon anacron

# Set return value to return value of last command

    RETVAL=$?

# If the previous command went well (exit 0), procede with the locking.

    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/anacron
    echo
    return $RETVAL
}

# initializing the stop procedure:

stop() {

# If anacron is running, find its process number and kill it.

    if test "x`pidof anacron`" != x; then
        echo -n $"Stopping $prog: "
        killproc anacron
        echo
    fi
    RETVAL=$?

# If all went well, remove the lock.

    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/anacron
    return $RETVAL
}

# Definition of the cases for the first argument:

case "$1" in
        start)
            start
            ;;

        stop)
            stop
            ;;

        status)
            status anacron
            ;;
        restart)
            stop
            start
            ;;
        condrestart)
            if test "x`pidof anacron`" != x; then
                stop
                start
            fi
            ;;

        *)
            echo $"Usage: $0 {start|stop|restart|condrestart|status}"
            exit 1

esac

# Pass OK code.

exit 0
Home
© 1995-2010 Machtelt Garrels - tille - Powered by vIm - Best viewed with your eyes - Validated by W3C - Last update 20100511