1 .\" $FreeBSD: src/usr.bin/getopt/getopt.1,v 1.10.2.5 2002/12/29 16:35:39 schweikh Exp $
2 .\" $DragonFly: src/usr.bin/getopt/getopt.1,v 1.2 2003/06/17 04:29:27 dillon Exp $
9 .Nd parse command options
11 .Nm args=\`getopt Ar optstring $*\`
12 ; errcode=$?; set \-\- $args
16 utility is used to break up options in command lines for easy parsing by
17 shell procedures, and to check for legal options.
19 is a string of recognized option letters (see
21 if a letter is followed by a colon, the option
22 is expected to have an argument which may or may not be
23 separated from it by white space.
26 is used to delimit the end of the options.
31 in the arguments at the end of the options,
32 or recognize it if used explicitly.
34 (\fB$1 $2\fR ...) are reset so that each option is
37 and in its own shell argument;
38 each option argument is also in its own shell argument.
40 The following code fragment shows how one might process the arguments
41 for a command that can take the options
47 which requires an argument.
49 .Bd -literal -offset indent
50 args=\`getopt abo: $*\`
51 # you should not use \`getopt abo: "$@"\` since that would parse
52 # the arguments differently from what the set command below does.
59 # You cannot use the set command with a backquoted getopt directly,
60 # since the exit code from getopt would be shadowed by those of set,
61 # which is zero by definition.
67 echo flag $i set; sflags="${i#-}$sflags";
70 echo oarg is "'"$2"'"; oarg="$2"; shift;
76 echo single-char flags: "'"$sflags"'"
77 echo oarg is "'"$oarg"'"
80 This code will accept any of the following as equivalent:
82 .Bd -literal -offset indent
84 cmd \-a \-o arg file file
85 cmd \-oarg -a file file
86 cmd \-a \-oarg \-\- file file
95 utility prints an error message on the standard error output and exits with
96 status > 0 when it encounters an option letter not included in
101 working from a Bell Labs manual page.
102 Behavior believed identical to the Bell version.
111 Arguments containing white space or embedded shell metacharacters
112 generally will not survive intact; this looks easy to fix but
113 isn't. People trying to fix
115 or the example in this manpage should check the history of this file
119 The error message for an invalid option is identified as coming
122 rather than from the shell procedure containing the invocation
125 this again is hard to fix.
127 The precise best way to use the
129 command to set the arguments without disrupting the value(s) of
130 shell options varies from one shell version to another.
132 Each shellscript has to carry complex code to parse arguments halfway
133 correctly (like the example presented here). A better getopt-like tool
134 would move much of the complexity into the tool and keep the client
135 shell scripts simpler.