How to Write a "USAGE" Message in a Shell Script

When you write a script and set up user interaction, generally the script expects a certain type of user input. For example, if the script prints a request for an age, it expects you to enter a numeric value. If you enter a name instead, the script might attempt an arithmetic operation on the variable and get an error.

The script should verify that the type of input and the number of values input are correct. If they are not correct, then the script can print an error message in the form of a USAGE message; for example:

if (( $# != 2 ))
then
        print “USAGE: $0 arg1 arg2 “
        exit
fi

In this case, the script expects two positional parameters to be entered when the script is run. If you do not provide the two parameters, the script prints out the USAGE message.

Including the USAGE message is a good programming practice. It is the conventional way to notify the person that executes the script that execution was not done correctly. Most operating system commands provide this type of information when you try to execute a command with an undefined option, such as ls -z.

$ ls -z
ls: illegal option -- z
usage: ls -1RaAdCxmnlhogrtuvVcpFbqisfHLeE@ [files]
$ cat /etc/init.d/volmgt
#!/sbin/sh

case "$1" in
'start')
       if [ -f /etc/vold.conf -a -f /usr/sbin/vold -a \
	   "${_INIT_ZONENAME:=`/sbin/zonename`}" = "global" ]; then
	   echo 'volume management starting.'
	   svcadm enable svc:/system/filesystem/volfs:default
	   fi
	   ;;
'stop')
        svcadm disable svc:/system/filesystem/volfs:default
        ;;
*)
       echo "Usage: $0 { start | stop }"
       exit 1
       ;;
esac
exit 0