getoptexternal command to parse shell file options |
Command |
getopt
[-c
cmdname]
optiondesc argument ...
getopt
command is often used in shell scripts to parse
command line options. The first command argument, optiondesc, contains
each option letter that is valid in the following command argument
strings. An option letter followed by a colon (:
) means that the
preceding option letter requires a further argument (as in
-o
file).
getopt
considers each argument that begins with a
-
to be a potential option and prints an error if it does not find
the argument in optiondesc. Scanning for further options stops at
the first argument which does not begin with -
or with an
argument that is --
. In either case, the options are separated from
the rest of the non-option argument strings by a --
string.
The most common construct for using getopt
is
This may be used inside the MKS KornShell to parse the arguments to a shell script; seeset - - $(getopt [-c cmdname] optiondesc "$@")
sh
for more about the shell.
-c
cmdnameuses cmdname rather than getopt
when
displaying error messages.
which parses thegetopt -c diff befhnmD: -eh -D string file1 file2
diff
command line
options, would produce the following output:
The following is a more realistic and complex example of using-e -h -D string -- file1 file2
getopt
in a shell script.
# Example illustrating use of getopt command. This # shell script would implement the paste command, # using getopt to process options, if the underlying # functionality was embedded in hypothetical utilities # hpaste and vpaste, which perform horizontal and # vertical pasting respectively. # paste=vpaste # default is vertical pasting seplist="\t" # default separator is tab set -- $(getopt -c $0 d:s "$@") if [ $? -ne 0 ] then print >&2 "Usage: $0 [-s] [-d seplist] file ..." exit 1 fi for o do case "$o" in -d) shift; seplist="$1"; shift;; -s) paste=hpaste; shift;; --) shift; break;; esac done # perform actual paste command $paste -d "$seplist" "$@"
0
Successful completion.
1
Failure due to any of the following:
-c