getopt

external command to parse shell file options 

Command


SYNOPSIS

getopt [-c cmdname] optiondesc argument ...


DESCRIPTION

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 (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

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.

Options

-c cmdname 

uses cmdname rather than getopt when displaying error messages.


EXAMPLE

The command:

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" "$@"

DIAGNOSTICS

Possible exit status values are:

0 

Successful completion.

1 

Failure due to any of the following:

— unknown command line option
— missing cmdname after -c
— invalid optiondesc
optiondesc that expected an argument but did not have one


PORTABILITY

UNIX System V. Windows 7. Windows Server 2008 R2. Windows 8. Windows Server 2012. Windows 10. Windows Server 2016.


AVAILABILITY

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


SEE ALSO

Commands:
diff, getopts, sh


PTC MKS Toolkit 10.1 patch 1 Documentation Build 2.