Bash/Parsing command line arguments using getopts

From ProgrammingExamples
< Bash
Revision as of 20:59, 20 April 2011 by Griswolf (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This is an example of looping over the command line parameters, handling flags and arguments. To do it right, I ended up showing several other things too. The critical bits are

  • looping by checking the number of remaining args $#
  • using case / esac, case tags xxx), shift and ;;
  • using cat <<EOM ... EOM to provide a multi-line message
#!/bin/bash
 
globalVariableStrings=''  # by default, bash variables are strings
declare -i globalVariableInt=0 # but if you know it's an int, declare it so
while [[ $# -gt 0 ]] ; do # $# is the count of command line args
  case $1 in              # $1 is the first (remaining) arg. 
  # case tags can be simple regular expressions. cat <<EOM cats everything up to a solo EOM on a line
  -h|--h*)cat <<EOM       
Usage: $(basename $0) [flags] [arguments]
 -h/--help: Show this message and exit
 -i value /--int=value: handle an integer flag. Last one wins
 <argument> handle a non-flag argument. Each seen is appended
EOM
  exit 0 ;;               # exit 0 flags 'success'. ;; shows end of a case statement
  -i) shift;              # shift removes the first arg (-i here)
       globalVariableInt=$1  # set the integer value
       shift ;;           # remove the integer value and drop from the case block
  --int=*) 
       globalVariableInt=$(echo $1|cut -f2 -d=) # -f: Which field; -d: what delimiter
       shift ;;           # as always
  *) globalVariableStrings="$globalVariableStrings $1" # append argument
     shift ;;             # as always
  esac
done
echo "The integer is $globalVariableInt"
for s in $globalVariableStrings ; do
  echo "You entered argument '$s'"
done