8 .Nd parse command options
10 .Nm args=\`getopt Ar optstring $*\`
11 ; errcode=$?; set \-\- $args
15 utility is used to break up options in command lines for easy parsing by
16 shell procedures, and to check for legal options.
18 is a string of recognized option letters (see
20 if a letter is followed by a colon, the option
21 is expected to have an argument which may or may not be
22 separated from it by white space.
25 is used to delimit the end of the options.
30 in the arguments at the end of the options,
31 or recognize it if used explicitly.
33 (\fB$1 $2\fR ...) are reset so that each option is
36 and in its own shell argument;
37 each option argument is also in its own shell argument.
41 utility prints an error message on the standard error output and exits with
42 status > 0 when it encounters an option letter not included in
45 The following code fragment shows how one might process the arguments
46 for a command that can take the options
52 which requires an argument.
53 .Bd -literal -offset indent
54 args=\`getopt abo: $*\`
55 # you should not use \`getopt abo: "$@"\` since that would parse
56 # the arguments differently from what the set command below does.
62 # You cannot use the set command with a backquoted getopt directly,
63 # since the exit code from getopt would be shadowed by those of set,
64 # which is zero by definition.
68 echo "flag $1 set"; sflags="${1#-}$sflags"
72 echo "oarg is '$2'"; oarg="$2"
80 echo "single-char flags: '$sflags'"
81 echo "oarg is '$oarg'"
84 This code will accept any of the following as equivalent:
85 .Bd -literal -offset indent
86 cmd \-aoarg file1 file2
87 cmd \-a \-o arg file1 file2
88 cmd \-oarg -a file1 file2
89 cmd \-a \-oarg \-\- file1 file2
98 working from a Bell Labs manual page.
99 Behavior believed identical to the Bell version.
108 Arguments containing white space or embedded shell metacharacters
109 generally will not survive intact; this looks easy to fix but
113 or the example in this manpage should check the history of this file
117 The error message for an invalid option is identified as coming
120 rather than from the shell procedure containing the invocation
123 this again is hard to fix.
125 The precise best way to use the
127 command to set the arguments without disrupting the value(s) of
128 shell options varies from one shell version to another.
130 Each shellscript has to carry complex code to parse arguments halfway
131 correctly (like the example presented here).
132 A better getopt-like tool
133 would move much of the complexity into the tool and keep the client
134 shell scripts simpler.