Bash/Parsing command line arguments using getopts

From ProgrammingExamples
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

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

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.

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

Example usages: -c test1 -n test2 -c test3 -i -h -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.