Bash/Parsing command line arguments using getopts

From ProgrammingExamples
< Bash
Revision as of 22:02, 4 October 2011 by Bandtank (Talk | contribs)

Jump to: navigation, search

Handling command line arguments can be done many ways, but few will be as elegant and streamlined as the built-in shell command called getopts. Note: getopt is the older version and should not be used as it is far less robust.

Getopts shifts the data and sets an exit status of false when there is nothing left to do. Because of this behavior, getopts works well in a while loop as follows:

while getopts ...; do
  ...
done

Often used in conjunction with getopts is the following conditional statement to force a certain number of arguments to be supplied:

#Check to see if the right number of arguments were supplied
if [ $# -lt 1 ] ; then
  ...
fi


The following script shows the usage of getopts. Getopts can't handle long options and will stop processing arguments when it hits the "--" argument (end of options). To specify an argument, the first letter of the word to be used as a switch is placed after the getopts command with an optional ":" if it also requires an additional parameter. An example program can be seen below.

#!/bin/bash
 
#Set a default value for the $cell variable
cell="test"
 
#Check to see if at least one argument was specified
if [ $# -lt 1 ] ; then
   echo "You must specify at least 1 argument."
   exit 1
fi
 
#Process the arguments
while getopts c:hin: opt
do
   case "$opt" in
      c) cell=$OPTARG;;
      h) usage;;
      i) info="yes"
      n) name=$OPTARG;;
      \?) usage;;
   esac
done


Example usages:

getopts_example.sh -c test1 -n test2
getopts_example.sh -c test3 -i
getopts_example.sh -h
getopts_example.sh -a


Example 1 would assign "test1" to the $cell variable and "test2" to the $name variable.

Example 2 would assign "test3" to the $cell variable, $name would not exist, and "yes" would be assigned to $info.

Example 3 would call the usage function.

Example 4 would cause getopts to display an error to stderr and then exit after calling the usage function.