Museum

Home

Lab Overview

Retrotechnology Articles

⇒ Online Manual

Media Vault

Software Library

Restoration Projects

Artifacts Sought

Related Articles

sh(1)

csh(1)

getopt(3C)

GETOPT(1)  —  USER COMMANDS

NAME

getopt − parse command options in shell scripts

SYNOPSIS

set −− ‘getopt optstring $∗‘

DESCRIPTION

getopt is used to break up options in command lines for easy parsing by shell scripts, and to check for legal options.  optstring is a string of option letters to recognize, (see getopt(3C)).  If a letter is followed by a colon, the option is expected to have an argument — which may or may not be separated by white space. 

(The −− following set indicates that the Bourne shell is to pass arguments beginning with a dash as parameters to the script.) 

If −− appears on the command line that invokes the script, getopt uses it to delimit the end of options it is to parse (see example below).  If used explicitly, getopt will recognize it; otherwise, getopt will generate it at the first arugment it encounters that has no −.  In either case, getopt places it at the end of the options.  The positional parameters ($1 $2 optstring is broken out and preceded by a −, along with the argument (if any) for each. 

EXAMPLE

The following code fragment shows how one might process the arguments for a command that can take the options a or b, as well as the option o, which requires an argument:

#! /bin/sh
set −− getopt abo: $∗‘
if [ $? != 0 ]
then
echo $USAGE
exit 2
fi
for i in $∗
do
case $i in
−a │ −b)FLAG=$i; shift;;
−o)OARG=$2; shift 2;;
−−)shift; break;;
esac
done

This code will accept any of the following command lines as equivalent:

cmd −a −o arg  f1  f2
cmd −aoarg  f1  f2
cmd −oarg −a  f1  f2
cmd −a −oarg −−  f1  f2

DIAGNOSTICS

getopt prints an error message on the standard error when it encounters an option letter not included in optstring.

SEE ALSO

sh(1), csh(1), getopt(3C)

Sun Release 3.2  —  Last change: 28 March 1986

Typewritten Software • bear@typewritten.org • Edmonds, WA 98026