Foil 10 - Subroutine to parse command arguments (2/2)

 1 ######## Get the remaining command line options
 2 shift_count="`expr $OPTIND - 1`"
 3 if [ "$shift_count" -gt 0 ]
 4   then
 5     shift "$shift_count"
 6   fi
 7 
 8 ######## You cannot specify the file or command, not both
 9 if [ "$file_flag" = "yes" -a $# -gt 0 ]
10   then
11     echo "Must supply file name or command, not both" ; exit 8
12   fi
13 
14 if [ "$file_flag" = "no" -a $# -eq 0 ]
15   then
16     echo "Must supply file name or command" ; exit 8
17   fi
18 
19 } # End of option_sub function
20 
21 #---------------------------------------------------------------------
22 # Since we are calling another routine, the shell will reinterpret all
23 # passed options, we must use "$@" so quoted strings are not split.
24 option_sub "$@"       # Call function to parse cmd line options    #10

This is the second 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 2 gets the count of the options handled by getopts. These are still in the shell command buffer so we need to eliminate them from further processing.
  • Lines 3-6 get to the remaining arguments.
  • Lines 9-17 show how more detailed checks can be made for conflicting or missing options.
  • Line 24 shows how this subroutine can be called and passed the original command line arguments so any quoted strings are processed as a unit.

    Since all variables are globally available and changeable by the subroutine, the values set in the subroutine are available to the main and vice-versa.

    Previous   Next   Index