xref: /titanic_44/usr/src/man/man1/getopts.1 (revision 812e8c05270efb3334ff7b081079ed4b71c712c8)
te
Copyright 1989 AT&T
Copyright 1992, X/Open Company Limited All Rights Reserved
Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved
Portions Copyright (c) 1982-2007 AT&T Knowledge Ventures
Sun Microsystems, Inc. gratefully acknowledges The Open Group for permission to reproduce portions of its copyrighted documentation. Original documentation from The Open Group can be obtained online at
http://www.opengroup.org/bookstore/.
The Institute of Electrical and Electronics Engineers and The Open Group, have given us permission to reprint portions of their documentation. In the following statement, the phrase "this text" refers to portions of the system documentation. Portions of this text are reprinted and reproduced in electronic form in the Sun OS Reference Manual, from IEEE Std 1003.1, 2004 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2004 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between these versions and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html.
This notice shall appear on any product containing this material.
The contents of this file are subject to the terms of the Common Development and Distribution License (the "License"). You may not use this file except in compliance with the License.
You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE or http://www.opensolaris.org/os/licensing. See the License for the specific language governing permissions and limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and include the License file at usr/src/OPENSOLARIS.LICENSE. If applicable, add the following below this CDDL HEADER, with the fields enclosed by brackets "[]" replaced with your own identifying information: Portions Copyright [yyyy] [name of copyright owner]
getopts 1 "2 Nov 2007" "SunOS 5.11" "User Commands"
NAME
getopts - parse utility options
SYNOPSIS

/usr/bin/getopts optstring name [arg...]
"sh"

getopts optstring name [argument]...
"ksh"

getopts optstring name [arg]...
"ksh93"

getopts [-a name] optstring name [arg]...
DESCRIPTION

The getopts utility can be used to retrieve options and option-arguments from a list of parameters.

Each time it is invoked, the getopts utility places the value of the next option in the shell variable specified by the name operand and the index of the next argument to be processed in the shell variable OPTIND. Whenever the shell is invoked, OPTIND is initialized to 1.

When the option requires an option-argument, the getopts utility places it in the shell variable OPTARG. If no option was found, or if the option that was found does not have an option-argument, OPTARG is unset.

If an option character not contained in the optstring operand is found where an option character is expected, the shell variable specified by name is set to the question-mark ( ? ) character. In this case, if the first character in optstring is a colon (:, the shell variable OPTARG is set to the option character found, but no output is written to standard error; otherwise, the shell variable OPTARG is unset and a diagnostic message is written to standard error. This condition is considered to be an error detected in the way arguments were presented to the invoking application, but is not an error in getopts processing.

If an option-argument is missing:

If the first character of optstring is a colon, the shell variable specified by name is set to the colon character and the shell variable OPTARG is set to the option character found.

Otherwise, the shell variable specified by name is set to the question-mark character (?), the shell variable OPTARG is unset, and a diagnostic message is written to standard error. This condition is considered to be an error detected in the way arguments were presented to the invoking application, but is not an error in getopts processing; a diagnostic message is written as stated, but the exit status is zero.

When the end of options is encountered, the getopts utility exits with a return value greater than zero; the shell variable OPTIND is set to the index of the first non-option-argument, where the first -\|- argument is considered to be an option-argument if there are no other non-option-arguments appearing before it, or the value $# + 1 if there are no non-option-arguments; the name variable is set to the question-mark character. Any of the following identifies the end of options: the special option -\|-, finding an argument that does not begin with a -, or encountering an error.

The shell variables OPTIND and OPTARG are local to the caller of getopts and are not exported by default.

The shell variable specified by the name operand, OPTIND and OPTARG affect the current shell execution environment.

If the application sets OPTIND to the value 1, a new set of parameters can be used: either the current positional parameters or new arg values. Any other attempt to invoke getopts multiple times in a single shell execution environment with parameters (positional parameters or arg operands) that are not the same in all invocations, or with an OPTIND value modified to be a value other than 1, produces unspecified results.

"sh"

getopts is a built-in Bourne shell command used to parse positional parameters and to check for valid options. See sh(1). It supports all applicable rules of the command syntax standard (see Rules 3-10, Intro(1)). It should be used in place of the getopt command.

optstring must contain the option letters the command using getopts recognizes. If a letter is followed by a colon, the option is expected to have an argument, or group of arguments, which must be separated from it by white space.

Each time it is invoked, getopts places the next option in the shell variable name and the index of the next argument to be processed in the shell variable OPTIND. Whenever the shell or a shell script is invoked, OPTIND is initialized to 1.

When an option requires an option-argument, getopts places it in the shell variable OPTARG.

If an illegal option is encountered, ? is placed in name.

When the end of options is encountered, getopts exits with a non-zero exit status. The special option - can be used to delimit the end of the options.

By default, getopts parses the positional parameters. If extra arguments (argument .\|.\|.) are specified on the getopts command line, getopts parses them instead.

/usr/lib/getoptcvt reads the shell script in filename, converts it to use getopts instead of getopt, and writes the results on the standard output.

So that all new commands adhere to the command syntax standard described in Intro(1), they should use getopts or getopt to parse positional parameters and check for options that are valid for that command.

getopts prints an error message on the standard error when it encounters an option letter not included in optstring.

Although the following command syntax rule (see Intro(1)) relaxations are permitted under the current implementation, they should not be used because they can not be supported in future releases of the system. As in the EXAMPLES section below, -a and -b are options, and the option -o requires an option-argument.

The following example violates Rule 5: options with option-arguments must not be grouped with other options:

example% cmd -aboxxx filename

The following example violates Rule 6: there must be white space after an option that takes an option-argument:

example% cmd -ab oxxx filename

Changing the value of the shell variable OPTIND or parsing different sets of arguments can lead to unexpected results.

"ksh"

Checks arg for legal options. If arg is omitted, the positional parameters are used. An option argument begins with a + or a -. An option not beginning with + or - or the argument - ends the options. optstring contains the letters that getopts recognizes. If a letter is followed by a :, that option is expected to have an argument. The options can be separated from the argument by blanks.

getopts places the next option letter it finds inside variable name each time it is invoked with a + prepended when arg begins with a +. The index of the next arg is stored in OPTIND. The option argument, if any, gets stored in OPTARG.

A leading : in optstring causes getopts to store the letter of an invalid option in OPTARG, and to set name to ? for an unknown option and to : when a required option is missing. Otherwise, getopts prints an error message. The exit status is non-zero when there are no more options.

getopts supports both traditional single-character short options and long options defined by Sun's Command Line Interface Paradigm (CLIP).

Each long option is an alias for a short option and is specified in parentheses following its equivalent short option. For example, you can specify the long option file as an alias for the short option f using the following script line:

getopts "f(file)" opt

Precede long options on the command line with -- or ++. In the example above, --file on the command line would be the equivalent of -f, and ++file on the command line would be the equivalent of +f.

Each short option can have multiple long option equivalents, although this is in violation of the CLIP specification and should be used with caution. You must enclose each long option equivalent parentheses, as follows:

getopts "f:(file)(input-file)o:(output-file)"

In the above example, both --file and --input-file are the equivalent of -f, and --output-file is the equivalent of -o.

The variable name is always set to a short option. When a long option is specified on the command line, name is set to the short-option equivalent.

For a further discussion of the Korn shell's getopts built-in command, see the previous discussion in the Bourne shell (sh) section of this manpage.

"ksh93"

The getopts utility can be used to retrieve options and arguments from a list of arguments specified by args or the positional parameters if arg is omitted. It can also generate usage messages and a manual page for the command based on the information in optstring.

Each time it is invoked, the getopts utility places the value of the next option in the shell variable specified by the name operand and the index of the next argument to be processed in the shell variable OPTIND. When the shell is invoked OPTIND is initialized to 1. When an option requires or permits an option argument, getopts places the option argument in the shell variable OPTARG. Otherwise OPTARG is set to 1 when the option is set and 0 when the option is unset.

The optstring string consists of alphanumeric characters, the special characters +, -, ?, :, and SPACE or character groups enclosed in [...]. Character groups can be nested in {...}. Outside of a [...] group, a single NEWLINE followed by zero or more blanks is ignored. One or more blank lines separate the options from the command argument synopsis.

Each [...] group consists of an optional label, optional attributes separated by :, and an optional description string following ?. The characters from the ? to the end of the next ] are ignored for option parsing and short usage messages. They are used for generating verbose help or man pages. The : character can not appear in the label. The ? character must be specified as ?? in the label and the ] character must be specified as ]] in the description string. Text between two \eb (backspace) characters indicates that the text should be emboldened when displayed. Text between two \ea (bell) characters indicates that the text should be emphasized or italicized when displayed. Text between two \ev (vertical tab) characters indicates that the text should displayed in a fixed-width font. Text between two \ef (form feed) characters is replaced by the output from the shell function whose name is that of the enclosed text.

All output from this interface is written to the standard error.

There are several group types:

1. A group of the form

[-[version][flag[number]]...[?text]]
which appears as the first group enables the extended interface. version specifies the interface version, currently 1. The latest version is assumed if version is omitted. Future enhancements can increment version, but all versions are supported. text typically specifies an SCCS or CVS identification string. Zero or more flags with optional number values can be specified to control option parsing. The flags are:

c

Cache this optstring for multiple passes. Used to optimize built-ins that can be called many times within the same process.

i

Ignore this optstring when generating help. Used when combining optstring values from multiple passes.

l

Display only long option names in help messages.

o

The - option character prefix is optional. This supports the obsolete ps(1) option syntax.

p

The number specifies the number of - characters that must prefix long option names. The default is 2. 0, 1 or 2 are accepted, for example p0 for dd(1M) and p1 for find(1).

s

The number specifies the manual page section number, 1 by default.

2. An option specification of the form [option[!][=number][:longname][?text]]. In this case the first field is the option character, which is the value returned in the name operand when the option is matched. If there is no option character then a two or more digit number should be specified. This number is returned as the value of the name operand if the long option is matched. If option is followed by a ! then the option character sense is the inverse of the longname sense. For options that do not take values OPTARG is set to 0 for ! inverted option characters and 1 otherwise. =number optionally specifies a number to be returned in the name operand instead of the option character. A longname is specified by --longname and is matched by the shortest non-ambiguous prefix of all long options. An * in the longname field indicates that only characters up to that point need to match, provided any additional characters match exactly. The enclosing [ and ] can be omitted for an option that does not have a longname or descriptive text.

3. An option argument specification. Options that take arguments can be followed by :, indicating a string value or #, indicating a numeric value, and an option argument specification. An option argument specification consists of the option argument name as field 1. The remaining : separated fields are a type name and zero or more of the special attribute words listof, oneof, and ignorecase. A default option value can be specified in the final field as :=default. The option argument specification can be followed by a list of option value descriptions enclosed in braces. A long option that takes an argument is specified as --longname=value. If the : or # is followed by ?, the option argument is optional. If only the option character form is specified then the optional argument value is not set if the next argument starts with - or +.

4. An option value description.

5. An argument specification. A list of valid option argument values can be specified by enclosing them inside a {...} following the option argument specification. Each of the permitted values can be specified with a [...] containing the value followed by a description.

6. A group of the form [+\en...] displays the characters representing ... in fixed-width font without adding line breaks.

7. A group of the form [+name?text] specifies a section name with descriptive text. If name is omitted, text is placed in a new paragraph.

8. A group of the form [-name?text] specifies entries for the IMPLEMENTATION section.

If the leading character of optstring is +, arguments beginning with + are also be considered options.

A leading : character or a : following a leading + in optstring affects the way errors are handled. If an option character or longname argument not specified in optstring is encountered when processing options, the shell variable whose name is name is set to the ? character. The shell variable OPTARG is set to the character found. If an option argument is missing or has an invalid value, then name is set to the : character and the shell variable OPTARG is set to the option character found. Without the leading :, name is set to the ? character, OPTARG is unset, and an error message is written to standard error when errors are encountered.

The end of options occurs when:

1. The special argument -- is encountered.

2. An argument that does not begin with a - is encountered.

3. A help argument is specified.

4. An error is encountered.

If OPTIND is set to the value 1, a new set of arguments can be used.

getopts can also be used to generate help messages containing command usage and detailed descriptions. Specify args as:

-?

Use this to generate a usage synopsis.

--??

Use this to generate a verbose usage message.

--??man

Use this to generate a formatted manual page.

--??api

Use this to generate an easy to parse usage message.

--??html

Use this to generate a man page in html format.

--??nroff

Use this to generate a man page in nroff format.

--??usage

Use this to list the current optstring.

--???name

Use this to list version=n, where n is greater than 0, if the option name is recognized by getopts.

When the end of options is encountered, getopts exits with a non-zero return value and the variable OPTIND is set to the index of the first non-option argument.

OPTIONS
"ksh93"

The following options are supported by ksh93:

-a name

Use name instead of the command name in usage messages.

OPERANDS

The following operands are supported:

optstring

A string containing the option characters recognised by the utility invoking getopts. If a character is followed by a colon, the option is expected to have an argument, which should be supplied as a separate argument. Applications should specify an option character and its option-argument as separate arguments, but getopts interprets the characters following an option character requiring arguments as an argument whether or not this is done. An explicit null option-argument need not be recognised if it is not supplied as a separate argument when getopts is invoked; see getopt(3C). The characters question-mark (?) and colon (:) must not be used as option characters by an application. The use of other option characters that are not alphanumeric produces unspecified results. If the option-argument is not supplied as a separate argument from the option character, the value in OPTARG is stripped of the option character and the -. The first character in optstring determines how getopts behaves if an option character is not known or an option-argument is missing.

name

The name of a shell variable that is set by the getopts utility to the option character that was found.

The getopts utility by default parses positional parameters passed to the invoking shell procedure. If args are specified, they are parsed instead of the positional parameters.

USAGE

Since getopts affects the current shell execution environment, it is generally provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following:

 (getopts abc value "$@")
 nohup getopts ...
 find . -exec getopts ... \e;

it does not affect the shell variables in the caller's environment.

Notice that shell functions share OPTIND with the calling shell even though the positional parameters are changed. Functions that want to use getopts to parse their arguments usually want to save the value of OPTIND on entry and restore it before returning. However, there are cases when a function wants to change OPTIND for the calling shell.

EXAMPLES

Example 1 Parsing and Displaying Arguments

The following example script parses and displays its arguments:

aflag=
bflag=
while getopts ab: name
do
 case $name in
 a) aflag=1;;
 b) bflag=1
 bval="$OPTARG";;
 ?) printf "Usage: %s: [-a] [-b value] args\en" $0
 exit 2;;
 esac
done
if [ ! -z "$aflag" ]; then
 printf "Option -a specified\en"
fi
if [ ! -z "$bflag" ]; then
 printf 'Option -b "%s" specified\en' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\en" "$*"

Example 2 Processing Arguments for a Command with Options

The following fragment of a shell program processes the arguments for a command that can take the options -a or -b. It also processes the option -o, which requires an option-argument:

while getopts abo: c
do
 case $c in
 a | b) FLAG=$c;;
 o) OARG=$OPTARG;;
 \e?) echo $USAGE
 exit 2;;
 esac
done
shift `expr $OPTIND - 1`

Example 3 Equivalent Code Expressions

This code example accepts any of the following as equivalent:

cmd -a -b -o "xxx z yy" filename
cmd -a -b -o "xxx z yy" -- filename
cmd -ab -o xxx,z,yy filename
cmd -ab -o "xxx z yy" filename
cmd -o xxx,z,yy -b -a filename
ENVIRONMENT VARIABLES

See environ(5) for descriptions of the following environment variables that affect the execution of getopts: LANG, LC_ALL, LC_CTYPE, LC_MESSAGES, and NLSPATH.

OPTIND

This variable is used by getopts as the index of the next argument to be processed.

OPTARG

This variable is used by getopts to store the argument if an option is using arguments.

EXIT STATUS

The following exit values are returned:

0

An option, specified or unspecified by optstring, was found.

>0

The end of options was encountered or an error occurred.

"ksh93"

The following exit values are returned by ksh93:

0

A specified option was found.

1

An end of options was encountered.

2

A usage or information message was generated.

ATTRIBUTES

See attributes(5) for descriptions of the following attributes:

"/usr/bin/getopts, sh, ksh"
ATTRIBUTE TYPEATTRIBUTE VALUE
Interface StabilityCommitted
StandardSee standards(5).
"ksh93"
ATTRIBUTE TYPEATTRIBUTE VALUE
Interface StabilityUncommitted
SEE ALSO

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

DIAGNOSTICS

Whenever an error is detected and the first character in the optstring operand is not a colon (:), a diagnostic message is written to standard error with the following information in an unspecified format:

The invoking program name is identified in the message. The invoking program name is the value of the shell special parameter 0 at the time the getopts utility is invoked. A name equivalent to

basename "$0"
can be used.

If an option is found that was not specified in optstring, this error is identified and the invalid option character is identified in the message.

If an option requiring an option-argument is found, but an option-argument is not found, this error is identified and the invalid option character is identified in the message.