Foil 09 - Subroutine to parse command arguments (1/2)

 1 #*********************************************************************
 2 # Function to validate and interpret user options on the cmd line.   *
 3 #*********************************************************************
 4 option_sub() {
 5 
 6 verbose="no" ; vflag="" ; file_flag=no  # Set defaults for options
 7 
 8 while getopts :vf: optname
 9   do
10     #echo "name=\"$optname\" IND=\"$OPTIND\" ARG=\"$OPTARG\"" 1>&2
11     case $optname in
12       v )
13         verbose="yes" ; vflag="-v"
14       ;;
15       f )
16         file_flag=yes ; mac_file="$OPTARG"
17       ;;
18       * )
19         emsg "Unknown option $name"
20         usage ; exit 3
21       ;;
22     esac
23   done                                                             #09

This is the first half of a subroutine that uses the getopts command to parse command line options. It can be easily adapted to changing operands and to detect optional and required "options".

  • Line 6 initializes the default values for the options. While Bourne does not complain about unitialized variables, it is always good practise to initialize variables before use.
  • Line 8 calls the getopts command until there are no more operands to process. the ":vf:" gives the letters of the valid operands and whether they have values or not. "optname" is assigned the letter of each flag in turn. See the man page for getopts for details.
  • Lines 11-22 save the value of each flag and operand along with unknown flags.
  • Line 20 calls a subroutine to output syntax hints.

    Previous   Next   Index