1getopts(1)                       User Commands                      getopts(1)
2
3
4

NAME

6       getopts - parse utility options
7

SYNOPSIS

9       /usr/bin/getopts optstring name [arg...]
10
11
12   sh
13       getopts optstring name [argument]...
14
15
16   ksh
17       getopts optstring name [arg]...
18
19
20   ksh93
21       getopts [-a name] optstring name [arg]...
22
23

DESCRIPTION

25   /usr/bin/getopts
26       The  getopts  utility  can be used to retrieve options and option-argu‐
27       ments from a list of parameters.
28
29
30       Each time it is invoked, the getopts utility places the  value  of  the
31       next option in the shell variable specified by the name operand and the
32       index of the next argument  to  be  processed  in  the  shell  variable
33       OPTIND. Whenever the shell is invoked, OPTIND is initialized to 1.
34
35
36       When the option requires an option-argument, the getopts utility places
37       it in the shell variable OPTARG. If no option  was  found,  or  if  the
38       option  that  was  found  does  not  have an option-argument, OPTARG is
39       unset.
40
41
42       If an option character not contained in the optstring operand is  found
43       where  an option character is expected, the shell variable specified by
44       name is set to the question-mark ( ? ) character. In this case, if  the
45       first  character  in optstring is a colon (:, the shell variable OPTARG
46       is set to the option character found, but no output is written to stan‐
47       dard  error;  otherwise, the shell variable OPTARG is unset and a diag‐
48       nostic message is written to standard error. This condition is  consid‐
49       ered to be an error detected in the way arguments were presented to the
50       invoking application, but is not an error in getopts processing.
51
52
53       If an option-argument is missing:
54
55           o      If the first character of optstring is a  colon,  the  shell
56                  variable specified by name is set to the colon character and
57                  the shell variable OPTARG is set  to  the  option  character
58                  found.
59
60           o      Otherwise,  the  shell  variable specified by name is set to
61                  the question-mark character (?), the shell  variable  OPTARG
62                  is  unset,  and  a diagnostic message is written to standard
63                  error. This condition is considered to be an error  detected
64                  in the way arguments were presented to the invoking applica‐
65                  tion, but is not an error in getopts processing; a  diagnos‐
66                  tic  message  is  written  as stated, but the exit status is
67                  zero.
68
69
70       When the end of options is encountered, the getopts utility exits  with
71       a  return  value greater than zero; the shell variable OPTIND is set to
72       the index of the first non-option-argument, where the first −− argument
73       is  considered  to  be  an  option-argument  if there are no other non-
74       option-arguments appearing before it, or the value $# + 1 if there  are
75       no  non-option-arguments; the name variable is set to the question-mark
76       character. Any of the following identifies the end of options: the spe‐
77       cial  option  −−,  finding an argument that does not begin with a , or
78       encountering an error.
79
80
81       The shell variables OPTIND and  OPTARG  are  local  to  the  caller  of
82       getopts and are not exported by default.
83
84
85       The  shell  variable  specified  by the name operand, OPTIND and OPTARG
86       affect the current shell execution environment.
87
88
89       If the application sets OPTIND to the value 1, a new set of  parameters
90       can  be  used: either the current positional parameters or new arg val‐
91       ues. Any other attempt to invoke getopts multiple  times  in  a  single
92       shell  execution  environment with parameters (positional parameters or
93       arg operands) that are not the same in  all  invocations,  or  with  an
94       OPTIND  value modified to be a value other than 1, produces unspecified
95       results.
96
97   sh
98       getopts is a built-in Bourne shell command  used  to  parse  positional
99       parameters  and  to check for valid options. See sh(1). It supports all
100       applicable rules of  the  command  syntax  standard  (see  Rules  3-10,
101       Intro(1)). It should be used in place of the getopt command.
102
103
104       optstring  must  contain  the  option letters the command using getopts
105       recognizes. If a letter is followed by a colon, the option is  expected
106       to  have  an  argument,  or group of arguments, which must be separated
107       from it by white space.
108
109
110       Each time it is invoked, getopts places the next option  in  the  shell
111       variable name and the index of the next argument to be processed in the
112       shell variable OPTIND. Whenever the shell or a shell script is invoked,
113       OPTIND is initialized to 1.
114
115
116       When  an  option  requires an option-argument, getopts places it in the
117       shell variable OPTARG.
118
119
120       If an illegal option is encountered, ? is placed in name.
121
122
123       When the end of options is encountered, getopts exits with  a  non-zero
124       exit status. The special option - can be used to delimit the end of the
125       options.
126
127
128       By default, getopts parses the positional parameters.  If  extra  argu‐
129       ments (argument ...) are specified on the getopts command line, getopts
130       parses them instead.
131
132
133       /usr/lib/getoptcvt reads the shell script in filename, converts  it  to
134       use  getopts  instead of getopt, and writes the results on the standard
135       output.
136
137
138       So that  all  new  commands  adhere  to  the  command  syntax  standard
139       described in Intro(1), they should use getopts or getopt to parse posi‐
140       tional parameters and check for options that are valid  for  that  com‐
141       mand.
142
143
144       getopts  prints  an error message on the standard error when it encoun‐
145       ters an option letter not included in optstring.
146
147
148       Although the following command syntax rule (see  Intro(1))  relaxations
149       are permitted under the current implementation, they should not be used
150       because they can not be supported in future releases of the system.  As
151       in the EXAMPLES section below, -a and -b are options, and the option -o
152       requires an option-argument.
153
154
155       The following example violates Rule 5:  options  with  option-arguments
156       must not be grouped with other options:
157
158         example% cmd -aboxxx filename
159
160
161
162
163       The  following example violates Rule 6: there must be white space after
164       an option that takes an option-argument:
165
166         example% cmd -ab oxxx filename
167
168
169
170
171       Changing the value of the shell variable OPTIND  or  parsing  different
172       sets of arguments can lead to unexpected results.
173
174   ksh
175       Checks arg for legal options. If arg is omitted, the positional parame‐
176       ters are used. An option argument begins with a + or a . An option not
177       beginning  with  +  or  or the argument - ends the options. optstring
178       contains the letters that getopts recognizes. If a letter  is  followed
179       by a :, that option is expected to have an argument. The options can be
180       separated from the argument by blanks.
181
182
183       getopts places the next option letter it  finds  inside  variable  name
184       each  time  it  is invoked with a + prepended when arg begins with a +.
185       The index of the next arg is stored in OPTIND. The option argument,  if
186       any, gets stored in OPTARG.
187
188
189       A  leading  :  in  optstring  causes  getopts to store the letter of an
190       invalid option in OPTARG, and to set name to ? for  an  unknown  option
191       and  to  : when a required option is missing. Otherwise, getopts prints
192       an error message. The exit status is non-zero when there  are  no  more
193       options.
194
195
196       getopts  supports  both  traditional single-character short options and
197       long options defined by Sun's Command Line Interface Paradigm (CLIP).
198
199
200       Each long option is an alias for a short option  and  is  specified  in
201       parentheses following its equivalent short option. For example, you can
202       specify the long option file as an alias for the short option  f  using
203       the following script line:
204
205         getopts "f(file)" opt
206
207
208
209
210       Precede  long options on the command line with -- or ++. In the example
211       above, --file on the command line would be the equivalent  of  -f,  and
212       ++file on the command line would be the equivalent of +f.
213
214
215       Each  short  option can have multiple long option equivalents, although
216       this is in violation of the CLIP specification and should be used  with
217       caution.  You  must enclose each long option equivalent parentheses, as
218       follows:
219
220         getopts "f:(file)(input-file)o:(output-file)"
221
222
223
224
225       In the above example, both --file and --input-file are  the  equivalent
226       of -f, and --output-file is the equivalent of -o.
227
228
229       The  variable  name is always set to a short option. When a long option
230       is specified on the command line,  name  is  set  to  the  short-option
231       equivalent.
232
233
234       For  a further discussion of the Korn shell's getopts built-in command,
235       see the previous discussion in the Bourne shell (sh)  section  of  this
236       manpage.
237
238   ksh93
239       The  getopts utility can be used to retrieve options and arguments from
240       a list of arguments specified by args or the positional  parameters  if
241       arg  is  omitted. It can also generate usage messages and a manual page
242       for the command based on the information in optstring.
243
244
245       Each time it is invoked, the getopts utility places the  value  of  the
246       next option in the shell variable specified by the name operand and the
247       index of the next argument  to  be  processed  in  the  shell  variable
248       OPTIND.  When  the shell is invoked OPTIND is initialized to 1. When an
249       option requires or permits  an  option  argument,  getopts  places  the
250       option  argument  in the shell variable OPTARG. Otherwise OPTARG is set
251       to 1 when the option is set and 0 when the option is unset.
252
253
254       The optstring string consists of alphanumeric characters,  the  special
255       characters +, -, ?, :, and SPACE or character groups enclosed in [...].
256       Character groups can be nested in {...}. Outside of a  [...]  group,  a
257       single  NEWLINE followed by zero or more blanks is ignored. One or more
258       blank lines separate the options from the command argument synopsis.
259
260
261       Each [...] group consists of an  optional  label,  optional  attributes
262       separated  by  :,  and  an optional description string following ?. The
263       characters from the ? to the end of the next ] are ignored  for  option
264       parsing  and short usage messages. They are used for generating verbose
265       help or man pages. The : character can not appear in the label.  The  ?
266       character must be specified as ?? in the label and the ] character must
267       be specified as ]] in the  description  string.  Text  between  two  \b
268       (backspace)  characters  indicates  that  the text should be emboldened
269       when displayed. Text between two \a (bell)  characters  indicates  that
270       the  text  should  be  emphasized  or  italicized  when displayed. Text
271       between two \v (vertical tab) characters indicates that the text should
272       displayed  in a fixed-width font. Text between two \f (form feed) char‐
273       acters is replaced by the output from the shell function whose name  is
274       that of the enclosed text.
275
276
277       All output from this interface is written to the standard error.
278
279
280       There are several group types:
281
282           1.     A group of the form
283
284                    [-[version][flag[number]]...[?text]]
285
286
287                  which appears as the first group enables the extended inter‐
288                  face.
289
290                  version specifies the interface version,  currently  1.  The
291                  latest  version  is  assumed  if  version is omitted. Future
292                  enhancements can increment version,  but  all  versions  are
293                  supported. text typically specifies an SCCS or CVS identifi‐
294                  cation string. Zero or more flags with optional number  val‐
295                  ues  can  be  specified to control option parsing. The flags
296                  are:
297
298                Cacche this optstring for multiple  passes.  Used  to  optimize
299                built-ins  that  can  be  called  many  times  within the same
300                process.
301
302
303           i    Ignore this optstring when generating help. Used when  combin‐
304                ing optstring values from multiple passes.
305
306
307           l    Display only long option names in help messages.
308
309
310           o    The  -  option character prefix is optional. This supports the
311                obsolete ps(1) option syntax.
312
313
314           p    The number specifies the number of - characters that must pre‐
315                fix  long  option  names.  The  default  is  2.  0, 1 or 2 are
316                accepted, for example p0 for dd(1M) and p1 for find(1).
317
318
319           s    The number specifies the manual  page  section  number,  1  by
320                default.
321
322
323           2.     An   option   specification  of  the  form  [option[!][=num‐
324                  ber][:longname][?text]]. In this case the first field is the
325                  option  character,  which  is the value returned in the name
326                  operand when the option is matched. If there  is  no  option
327                  character  then  a two or more digit number should be speci‐
328                  fied. This number is returned as the value of the name oper‐
329                  and  if the long option is matched. If option is followed by
330                  a ! then the option character sense is the  inverse  of  the
331                  longname  sense.  For options that do not take values OPTARG
332                  is set to 0 for ! inverted option characters  and  1  other‐
333                  wise.  =number  optionally specifies a number to be returned
334                  in the name operand instead of the option character. A long‐
335                  name is specified by --longname and is matched by the short‐
336                  est non-ambiguous prefix of all long options. An  *  in  the
337                  longname  field  indicates  that  only characters up to that
338                  point need to  match,  provided  any  additional  characters
339                  match  exactly.  The enclosing [ and ] can be omitted for an
340                  option that does not have a longname or descriptive text.
341
342           3.     An option argument specification. Options  that  take  argu‐
343                  ments  can be followed by :, indicating a string value or #,
344                  indicating a numeric value, and an option argument  specifi‐
345                  cation.  An  option  argument  specification consists of the
346                  option argument name as field 1. The remaining  :  separated
347                  fields  are  a  type  name  and  zero or more of the special
348                  attribute words listof, oneof,  and  ignorecase.  A  default
349                  option  value  can  be  specified  in  the  final  field  as
350                  :=default. The option argument specification can be followed
351                  by a list of option value descriptions enclosed in braces. A
352                  long option that takes an argument is specified  as  --long‐
353                  name=value. If the : or # is followed by ?, the option argu‐
354                  ment is optional. If only the option character form is spec‐
355                  ified  then  the  optional  argument value is not set if the
356                  next argument starts with - or +.
357
358           4.     An option value description.
359
360           5.     An argument specification. A list of valid  option  argument
361                  values  can  be  specified  by enclosing them inside a {...}
362                  following the option argument  specification.  Each  of  the
363                  permitted  values  can  be specified with a [...] containing
364                  the value followed by a description.
365
366           6.     A group of the form [+\n...] displays the characters  repre‐
367                  senting ... in fixed-width font without adding line breaks.
368
369           7.     A  group  of  the form [+name?text] specifies a section name
370                  with descriptive text. If name is omitted, text is placed in
371                  a new paragraph.
372
373           8.     A  group  of the form [-name?text] specifies entries for the
374                  IMPLEMENTATION section.
375
376
377       If the leading character of optstring is +, arguments beginning with  +
378       are also be considered options.
379
380
381       A leading : character or a : following a leading + in optstring affects
382       the way errors are handled. If an option character or longname argument
383       not  specified in optstring is encountered when processing options, the
384       shell variable whose name is name is set to the ? character. The  shell
385       variable OPTARG is set to the character found. If an option argument is
386       missing or has an invalid value, then name is set to  the  :  character
387       and  the  shell  variable  OPTARG is set to the option character found.
388       Without the leading :, name is set to the ? character, OPTARG is unset,
389       and  an  error  message  is  written  to standard error when errors are
390       encountered.
391
392
393       The end of options occurs when:
394
395           1.     The special argument -- is encountered.
396
397           2.     An argument that does not begin with a - is encountered.
398
399           3.     A help argument is specified.
400
401           4.     An error is encountered.
402
403
404       If OPTIND is set to the value 1, a new set of arguments can be used.
405
406
407       getopts can also be used to generate help messages  containing  command
408       usage and detailed descriptions. Specify args as:
409
410       -?           Use this to generate a usage synopsis.
411
412
413       --??         Use this to generate a verbose usage message.
414
415
416       --??man      Use this to generate a formatted manual page.
417
418
419       --??api      Use this to generate an easy to parse usage message.
420
421
422       --??html     Use this to generate a man page in html format.
423
424
425       --??nroff    Use this to generate a man page in nroff format.
426
427
428       --??usage    Use this to list the current optstring.
429
430
431       --???name    Use  this to list version=n, where n is greater than 0, if
432                    the option name is recognized by getopts.
433
434
435
436       When the end of options is encountered, getopts exits with  a  non-zero
437       return  value  and the variable OPTIND is set to the index of the first
438       non-option argument.
439

OPTIONS

441   ksh93
442       The following options are supported by ksh93:
443
444       -a name    Use name instead of the command name in usage messages.
445
446

OPERANDS

448       The following operands are supported:
449
450       optstring    A string containing the option  characters  recognised  by
451                    the  utility  invoking getopts. If a character is followed
452                    by a colon, the option is expected to  have  an  argument,
453                    which  should be supplied as a separate argument. Applica‐
454                    tions should specify an option character and  its  option-
455                    argument as separate arguments, but getopts interprets the
456                    characters following an option character  requiring  argu‐
457                    ments  as  an  argument  whether  or  not this is done. An
458                    explicit null option-argument need not be recognised if it
459                    is  not  supplied  as  a separate argument when getopts is
460                    invoked; see getopt(3C). The characters question-mark  (?)
461                    and  colon (:) must not be used as option characters by an
462                    application. The use of other option characters  that  are
463                    not  alphanumeric  produces  unspecified  results.  If the
464                    option-argument is not supplied  as  a  separate  argument
465                    from the option character, the value in OPTARG is stripped
466                    of the option character and the . The first character  in
467                    optstring  determines  how  getopts  behaves  if an option
468                    character is not known or an option-argument is missing.
469
470
471       name         The name of a shell variable that is set  by  the  getopts
472                    utility to the option character that was found.
473
474
475
476       The  getopts  utility by default parses positional parameters passed to
477       the invoking shell procedure. If args are specified,  they  are  parsed
478       instead of the positional parameters.
479

USAGE

481       Since  getopts  affects  the current shell execution environment, it is
482       generally provided as a shell regular built-in. If it is  called  in  a
483       subshell  or separate utility execution environment, such as one of the
484       following:
485
486               (getopts abc value "$@")
487                nohup getopts ...
488                find . -exec getopts ... \;
489
490
491
492       it does not affect the shell variables in the caller's environment.
493
494
495       Notice that shell functions share OPTIND with the  calling  shell  even
496       though  the  positional  parameters are changed. Functions that want to
497       use getopts to parse their arguments usually want to save the value  of
498       OPTIND  on  entry  and  restore it before returning. However, there are
499       cases when a function wants to change OPTIND for the calling shell.
500

EXAMPLES

502       Example 1 Parsing and Displaying Arguments
503
504
505       The following example script parses and displays its arguments:
506
507
508         aflag=
509         bflag=
510         while getopts ab: name
511         do
512              case $name in
513              a)      aflag=1;;
514              b)      bflag=1
515                      bval="$OPTARG";;
516              ?)     printf "Usage: %s: [-a] [-b value] args\n"  $0
517                     exit 2;;
518              esac
519         done
520         if [ ! -z "$aflag" ]; then
521            printf "Option -a specified\n"
522         fi
523         if [ ! -z "$bflag" ]; then
524              printf 'Option -b "%s" specified\n' "$bval"
525         fi
526         shift $(($OPTIND - 1))
527         printf "Remaining arguments are: %s\n" "$*"
528
529
530       Example 2 Processing Arguments for a Command with Options
531
532
533       The following fragment of a shell program processes the arguments for a
534       command  that  can  take  the  options  -a or -b. It also processes the
535       option -o, which requires an option-argument:
536
537
538         while getopts abo: c
539         do
540               case $c in
541              a | b)   FLAG=$c;;
542              o)       OARG=$OPTARG;;
543              \?)      echo $USAGE
544                 exit 2;;
545              esac
546         done
547         shift `expr $OPTIND − 1`
548
549
550       Example 3 Equivalent Code Expressions
551
552
553       This code example accepts any of the following as equivalent:
554
555
556         cmd -a -b -o "xxx z yy" filename
557         cmd -a -b -o "xxx z yy" -- filename
558         cmd -ab -o xxx,z,yy filename
559         cmd -ab -o "xxx z yy" filename
560         cmd -o xxx,z,yy -b -a filename
561
562
563

ENVIRONMENT VARIABLES

565       See environ(5) for descriptions of the following environment  variables
566       that  affect  the execution of getopts: LANG, LC_ALL, LC_CTYPE, LC_MES‐
567       SAGES, and NLSPATH.
568
569       OPTIND    This variable is used by getopts as the  index  of  the  next
570                 argument to be processed.
571
572
573       OPTARG    This  variable is used by getopts to store the argument if an
574                 option is using arguments.
575
576

EXIT STATUS

578       The following exit values are returned:
579
580       0     An option, specified or unspecified by optstring, was found.
581
582
583       >0    The end of options was encountered or an error occurred.
584
585
586   ksh93
587       The following exit values are returned by ksh93:
588
589       0    A specified option was found.
590
591
592       1    An end of options was encountered.
593
594
595       2    A usage or information message was generated.
596
597

ATTRIBUTES

599       See attributes(5) for descriptions of the following attributes:
600
601   /usr/bin/getopts, sh, ksh
602       ┌─────────────────────────────┬─────────────────────────────┐
603       │      ATTRIBUTE TYPE         │      ATTRIBUTE VALUE        │
604       ├─────────────────────────────┼─────────────────────────────┤
605       │Availability                 │SUNWcsu                      │
606       ├─────────────────────────────┼─────────────────────────────┤
607       │Interface Stability          │Committed                    │
608       ├─────────────────────────────┼─────────────────────────────┤
609       │Standard                     │See standards(5).            │
610       └─────────────────────────────┴─────────────────────────────┘
611
612   ksh93
613       ┌─────────────────────────────┬─────────────────────────────┐
614       │      ATTRIBUTE TYPE         │      ATTRIBUTE VALUE        │
615       ├─────────────────────────────┼─────────────────────────────┤
616       │Availability                 │SUNWcsu                      │
617       ├─────────────────────────────┼─────────────────────────────┤
618       │Interface Stability          │Uncommitted                  │
619       └─────────────────────────────┴─────────────────────────────┘
620

SEE ALSO

622       Intro(1), getoptcvt(1), ksh(1),  ksh93(1),  ps(1),  sh(1),  getopt(3C),
623       attributes(5), environ(5), standards(5)
624

DIAGNOSTICS

626       Whenever  an error is detected and the first character in the optstring
627       operand is not a colon (:), a diagnostic message is written to standard
628       error with the following information in an unspecified format:
629
630           o      The  invoking program name is identified in the message. The
631                  invoking program name is the  value  of  the  shell  special
632                  parameter  0  at  the time the getopts utility is invoked. A
633                  name equivalent to
634
635                    basename "$0"
636
637                  can be used.
638
639           o      If an option is found that was not specified  in  optstring,
640                  this error is identified and the invalid option character is
641                  identified in the message.
642
643           o      If an option requiring an option-argument is found,  but  an
644                  option-argument  is  not found, this error is identified and
645                  the invalid option character is identified in the message.
646
647
648
649SunOS 5.11                        2 Nov 2007                        getopts(1)
Impressum