Monday, May 16, 2011

A Bash Script Template

#!/bin/sh

#---------------------------------------
# Script Description/Usage:
# To perform start/stop/restart of ......
#---------------------------------------
# Modification History:
# Jan 01, 2011 : A.Nie : initial creation
#---------------------------------------
#

RETVAL=0

# Check input arguments
if [ $# -ne 1 ] ; then
  echo "Usage: `basename $0` {start|stop|restart}"
  RETVAL=1
  exit $RETVAL
fi

# Check running user
if [ `id -un` != "root" ] ; then
  echo "Must run the script as root, exiting..."
  RETVAL=2
  exit $RETVAL
fi

# Define variables
VAR1=VARVALUE1
......

# Start function
start() {
          ......
}

# Stop function
stop() {
          ......
}

# Restart function
restart() {
             stop
             start
}

# Main
# While LOOP
while [ condition ] ; do
  ......
done

# For LOOP
for VAR in ...... ; do
  ......
done

case "$1" in
start)
        start
        ;;
stop)
        stop
        ;;
restart)
        restart
        ;;
*)
        echo "Usage: $0 {start|stop|restart}"
        RETVAL=3
        ;;
esac

exit $RETVAL