Debian Codegraph @

ex33.sh

raw symbols SCIP
1 #!/bin/bash
2 # ex33.sh: Exercising getopts and OPTIND
3 # Script modified 10/09/03 at the suggestion of Bill Gradwohl.
4
5
6 # Here we observe how 'getopts' processes command-line arguments to script.
7 # The arguments are parsed as "options" (flags) and associated arguments.
8
9 # Try invoking this script with:
10 # 'scriptname -mn'
11 # 'scriptname -oq qOption' (qOption can be some arbitrary string.)
12 # 'scriptname -qXXX -r'
13 #
14 # 'scriptname -qr'
15 #+ - Unexpected result, takes "r" as the argument to option "q"
16 # 'scriptname -q -r'
17 #+ - Unexpected result, same as above
18 # 'scriptname -mnop -mnop' - Unexpected result
19 # (OPTIND is unreliable at stating where an option came from.)
20 #
21 # If an option expects an argument ("flag:"), then it will grab
22 #+ whatever is next on the command-line.
23
24 NO_ARGS=0
25 E_OPTERROR=85
26
27 if [ $# -eq "$NO_ARGS" ] # Script invoked with no command-line args?
28 then
29 echo "Usage: `basename $0` options (-mnopqrs)"
30 exit $E_OPTERROR # Exit and explain usage.
31 # Usage: scriptname -options
32 # Note: dash (-) necessary
33 fi
34
35
36 while getopts ":mnopq:rs" Option
37 do
38 case $Option in
39 m ) echo "Scenario #1: option -m- [OPTIND=${OPTIND}]";;
40 n | o ) echo "Scenario #2: option -$Option- [OPTIND=${OPTIND}]";;
41 p ) echo "Scenario #3: option -p- [OPTIND=${OPTIND}]";;
42 q ) echo "Scenario #4: option -q-\
43 with argument \"$OPTARG\" [OPTIND=${OPTIND}]";;
44 # Note that option 'q' must have an associated argument,
45 #+ otherwise it falls through to the default.
46 r | s ) echo "Scenario #5: option -$Option-";;
47 * ) echo "Unimplemented option chosen.";; # Default.
48 esac
49 done
50
51 shift $(($OPTIND - 1))
52 # Decrements the argument pointer so it points to next argument.
53 # $1 now references the first non-option item supplied on the command-line
54 #+ if one exists.
55
56 exit $?
57
58 # As Bill Gradwohl states,
59 # "The getopts mechanism allows one to specify: scriptname -mnop -mnop
60 #+ but there is no reliable way to differentiate what came
61 #+ from where by using OPTIND."
62 # There are, however, workarounds.