HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

A minimal init script

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
minimalinitscript

Problem

I tried looking up some good example init scripts, but all that I found were excessively complicated. So I wrote my own simple init script targeting CentOS 6. I tried to follow LSB where I understood what it says. CentOS uses chkconfig instead of the LSB comment block.

This is my first serious shell script ever. What do you guys think?

#!/bin/sh
# chkconfig: 2345 80 20
# description: Perforce server

. /etc/profile.d/p4d.sh

command_line='p4d -d'

running() {
    pgrep -fx "$command_line" > /dev/null
}

start() {
    if ! running; then
        $command_line > /dev/null
    fi
}

stop() {
    if running; then
        p4 admin stop > /dev/null
    fi
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart|force-reload)
        stop
        start
    ;;
    status)
        if running; then
            echo "Running"
        else
            echo "Stopped"
            exit 3
        fi
    ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|status}"
        exit 1
    ;;
esac

exit 0

Solution

It's clear, nicely formatted, and passes http://www.shellcheck.net/# with flying colors. I have only minor nitpicks.

The variable name command_line is too generic.
If you make it more descriptive,
for example start_command,
then the purpose of the pgrep line becomes easier to understand:
it should match whatever was used to start the command.

This maybe a matter of taste, but I like to place the ;; in case statements at the same indent level as the body of the statement, for example:

case "$1" in
    start)
        start
        ;;       # aligned with the commands, not the label
    stop)


I'm not really aware of a standard, but for what it's worth,
Vim's auto-indent function (and auto-reindent with gg=G) indents this way.
This writing style is also practical when folding is enabled in Vim,
making long case statement blocks appear like this:

case "$1" in
    start)
        --- # folded lines
    stop)
        --- # folded lines
    restart|force-reload)
        --- # folded lines


Well, this is really a nitpick, and a matter of taste,
your way is perfectly fine too.

Code Snippets

case "$1" in
    start)
        start
        ;;       # aligned with the commands, not the label
    stop)
case "$1" in
    start)
        --- # folded lines
    stop)
        --- # folded lines
    restart|force-reload)
        --- # folded lines

Context

StackExchange Code Review Q#80149, answer score: 2

Revisions (0)

No revisions yet.