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 8.1. Windows Server 2012 R2. Windows 10. Windows Server 2016. Windows Server 2019. Windows 11. Windows Server 2022.
PTC MKS Toolkit for Power Users
PTC MKS Toolkit for System Administrators
PTC MKS Toolkit for Developers
PTC MKS Toolkit for Interoperability
PTC MKS Toolkit for Professional Developers
PTC MKS Toolkit for Professional Developers 64-Bit Edition
PTC MKS Toolkit for Enterprise Developers
PTC MKS Toolkit for Enterprise Developers 64-Bit Edition
PTC MKS Toolkit 10.4 Documentation Build 39.