Example Usage of Getopt in a Shell Script

The following script is a real word example of getopts usage in a script.

It shows the basic usage of the typical do case statement and a help message in case of inproper arguments.

#!/bin/zsh

PROJECT=unknown

USAGE_MESSAGE="Usage: $0 [-h] [-p project]
   -h help
   -p {project} to work on"

while getopts hp: args
   do case "$args" in
      p) PROJECT="$OPTARG";;
      h) echo "${USAGE_MESSAGE}"
         exit 1;;
      :) echo "${USAGE_MESSAGE}"
         exit 1;;
      *) echo "${USAGE_MESSAGE}"
         exit 1;;
   esac
done

shift $(($OPTIND - 1))

PROJECT_HOME=${HOME}/Projects/${PROJECT}
echo "Launching project '${PROJECT}' in ${PROJECT_HOME}..."

cd ${PROJECT_HOME}/tools
source setenv.sh
cd ..

Have fun.