The 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
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
set - - $(getopt [-c cmdname] optiondesc "$@")
This may be used inside the MKS KornShell to parse the arguments to a shell script; see sh for more about the shell.
getopt -c diff befhnmD: -eh -D string file1 file2
which parses the diff command line options, would produce the following output:
-e -h -D string -- file1 file2
The following is a more realistic and complex example of using 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" "$@"
Possible exit status values are:
Failure due to any of the following:
UNIX System V. Windows 2000. Windows XP. Windows Server 2003. Windows Vista. Windows 7. Windows Server 2008. Windows 8. Windows Server 2012.
MKS Toolkit for Power Users
MKS Toolkit for System Administrators
MKS Toolkit for Developers
MKS Toolkit for Interoperability
MKS Toolkit for Professional Developers
MKS Toolkit for Enterprise Developers
MKS Toolkit for Enterprise Developers 64-Bit Edition
MKS Toolkit 9.5 Documentation Build 3.