getopt Command
Purpose
Parses command-line flags and parameters.
Syntax
getopt Format TokensDescription
The getopt command parses a list of tokens by using a
format that specifies expected flags and arguments. A flag is a single ASCII letter and when
followed by a : (colon) is expected to have an argument that might or might not be
separated from it by one or more tabs or spaces. You can include multibyte characters in arguments,
but not as a flag letter.
The getopt command completes processing when it finishes
reading all tokens or when it encounters the special token -- (double hyphen). The
getopt command then outputs the processed flags, a -- (double
hyphen), and any remaining tokens.
If a token fails to match a flag, the getopt command writes a message to standard error.
Examples
The getopt command can be used in a skeleton shell script to parse options, as in the following example:
#!/usr/bin/bsh
# parse command line into arguments
set -- `getopt a:bc $*`
# check result of parsing
if [ $? != 0 ]
then
exit 1
fi
while [ $1 != -- ]
do
case $1 in
-a) # set up the -a flag
AFLG=1
AARG=$2
shift;;
-b) # set up the -b flag
BFLG=1;;
-c) # set up the -c flag
CFLG=1;;
esac
shift # next flag
done
shift # skip --
# now do the work
.
.
.
set argv=`getopt OptionString $*`In each of the following examples, the getopt command processes the flags and arguments in the same way:
-a ARG -b -c-a ARG -bc-aARG -b -c-b -c -a ARG
Files
| Item | Description |
|---|---|
| /usr/bin/getopt | Contains the getopt command. |