getopt-demo
Download getopt-demo
1: #!/bin/bash
2: # Script showing use of getopt and here documents
3: #
4: # This script allows options of -m, -i, or -h or --help
5: # It doesn't really do anything, but it does show
6: # sophisticated command line argument processing
7: # and several advanced shell programming features.
8: # Note the "-m" option has a required argument,
9: # as does the equivalent "--mode" option.
10: #
11: # Written 2005 by Wayne Pollock, Tampa Florida USA.
12:
13: #set -x # uncomment this line to turn on debug mode
14:
15: PATH=/bin:/usr/bin
16:
17: # This strips off the pathname info from the scriptname,
18: # ("$0"), leaving just the last (filename) part:
19: SCRIPTNAME=${0##*/}
20:
21: # To avoid a lot of echo commands (and associated
22: # quoting issues) in some show_help function, you
23: # can use a "here" document. A "here" document
24: # is an embedded file within the script.
25: # Here's a sample:
26:
27: function show_help()
28: {
29: cat <<-EOF
30: $SCRIPTNAME: You are beyond any help,
31: so stop annoying me!!! :-)
32: ...
33: EOF
34: }
35:
36: # Parse out the args into a standard format:
37: ARGS=$(getopt -n $SCRIPTNAME -o m:ih -l mode:,help -- "$@")
38:
39: # if the getopt detected an error, display help and quit:
40: if [ $? -ne 0 ]
41: then
42: show_help
43: exit 1;
44: fi
45:
46: # Now reset the positional parameters:
47: # (The "eval" is needed in case any args were quoted by getopt.)
48: eval set -- $ARGS
49:
50: # Handle each arg. Usually this is a matter of setting
51: # some variable, to be tested later in the script.
52: # This loop processes each option, one at a time, until
53: # the end of options is found (marked with "--"). This
54: # code removes each arg as it is processed, so at the
55: # end, the positional parameters contain only the non-option
56: # command line args (for instance, filenames to work with):
57:
58: M_OPT=0
59: M_ARG='<none>'
60: I_OPT=0
61:
62: DONE=false
63: while [ "$DONE" != "true" ]
64: do
65: case "$1" in
66: -m|--mode) let '++M_OPT'
67: case "$2" in
68: -*) echo "*** Missing argument: $1" >&2; exit 1;;
69: *) M_ARG="$2"; shift ;;
70: esac
71: ;;
72:
73: -i) let '++I_OPT' ;;
74:
75: -h|--help) show_help ;;
76:
77: --) DONE=true ;;
78:
79: *) echo "***Illegal option: $1" >&2; exit 1 ;;
80:
81: esac
82:
83: shift # this deletes $1 and resets the positional parameters
84: done
85:
86: # At this point, the positional parameters contain the
87: # remaining command line arguments (not options), if any.
88:
89: # Rest of script goes here: ...
90: echo M_OPT=$M_OPT, M_ARG=$M_ARG, I_OPT=$I_OPT
91: echo remaining cmd line args: $*