[net.sources] public-domain getopt

henry@utzoo.UUCP (Henry Spencer) (04/13/84)

There has been so much interest in the public-domain getopt that I
have decided to post it to net.cog-eng as well as net.sources.  It's
not large (under 7KB) and there are various interested places that
don't get net.sources.  This is it.

I've included sources for both getopt(3) and getopt(1).  The latter
is a program that provides similar facilities to shell programs; it's
less successful than getopt(3) but still useful.  Please note the last
item in the BUGS section of getopt(1) carefully.

None of this software is derived from Bell software.  I had no access
to the source for Bell's versions at the time I wrote it.  This software
is hereby explicitly placed in the public domain.  It may be used for
any purpose on any machine by anyone.

Here are source for getopt(3), its manual page, source for getopt(1),
and its manual page.
-----
/*
 * getopt - get option letter from argv
 */

#include <stdio.h>

char	*optarg;	/* Global argument pointer. */
int	optind = 0;	/* Global argv index. */

static char	*scan = NULL;	/* Private scan pointer. */

extern char	*index();

int
getopt(argc, argv, optstring)
int argc;
char *argv[];
char *optstring;
{
	register char c;
	register char *place;

	optarg = NULL;

	if (scan == NULL || *scan == '\0') {
		if (optind == 0)
			optind++;
	
		if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
			return(EOF);
		if (strcmp(argv[optind], "--")==0) {
			optind++;
			return(EOF);
		}
	
		scan = argv[optind]+1;
		optind++;
	}

	c = *scan++;
	place = index(optstring, c);

	if (place == NULL || c == ':') {
		fprintf(stderr, "%s: unknown option -%c\n", argv[0], c);
		return('?');
	}

	place++;
	if (*place == ':') {
		if (*scan != '\0') {
			optarg = scan;
			scan = NULL;
		} else {
			optarg = argv[optind];
			optind++;
		}
	}

	return(c);
}
-----
.TH GETOPT 3 local
.DA 25 March 1982
.SH NAME
getopt \- get option letter from argv
.SH SYNOPSIS
.ft B
int getopt(argc, argv, optstring)
.br
int argc;
.br
char **argv;
.br
char *optstring;
.sp
extern char *optarg;
.br
extern int optind;
.ft
.SH DESCRIPTION
.I Getopt
returns the next option letter in
.I argv
that matches a letter in
.IR optstring .
.I Optstring
is a string of recognized option letters;
if a letter is followed by a colon, the option is expected to have
an argument that may or may not be separated from it by white space.
.I Optarg
is set to point to the start of the option argument on return from
.IR getopt .
.PP
.I Getopt
places in
.I optind
the
.I argv
index of the next argument to be processed.
Because
.I optind
is external, it is normally initialized to zero automatically
before the first call to 
.IR getopt .
.PP
When all options have been processed (i.e., up to the first
non-option argument),
.I getopt
returns
.BR EOF .
The special option
.B \-\-
may be used to delimit the end of the options;
.B EOF
will be returned, and
.B \-\-
will be skipped.
.SH SEE ALSO
getopt(1)
.SH DIAGNOSTICS
.I Getopt
prints an error message on
.I stderr
and returns a question mark
.RB ( ? )
when it encounters an option letter not included in
.IR optstring .
.SH EXAMPLE
The following code fragment shows how one might process the arguments
for a command that can take the mutually exclusive options
.B a
and
.BR b ,
and the options
.B f
and
.BR o ,
both of which require arguments:
.PP
.RS
.nf
main(argc, argv)
int argc;
char **argv;
{
	int c;
	extern int optind;
	extern char *optarg;
	\&.
	\&.
	\&.
	while ((c = getopt(argc, argv, "abf:o:")) != EOF)
		switch (c) {
		case 'a':
			if (bflg)
				errflg++;
			else
				aflg++;
			break;
		case 'b':
			if (aflg)
				errflg++;
			else
				bproc();
			break;
		case 'f':
			ifile = optarg;
			break;
		case 'o':
			ofile = optarg;
			break;
		case '?':
		default:
			errflg++;
			break;
		}
	if (errflg) {
		fprintf(stderr, "Usage: ...");
		exit(2);
	}
	for (; optind < argc; optind++) {
		\&.
		\&.
		\&.
	}
	\&.
	\&.
	\&.
}
.RE
.PP
A template similar to this can be found in
.IR /usr/pub/template.c .
.SH HISTORY
Written by Henry Spencer, working from a Bell Labs manual page.
Behavior believed identical to the Bell version.
.SH BUGS
It is not obvious how
`\-'
standing alone should be treated;  this version treats it as
a non-option argument, which is not always right.
.PP
Option arguments are allowed to begin with `\-';
this is reasonable but reduces the amount of error checking possible.
.PP
.I Getopt
is quite flexible but the obvious price must be paid:  there is much
it could do that it doesn't, like
checking mutually exclusive options, checking type of
option arguments, etc.
-----
#include <stdio.h>

main(argc, argv)
int argc;
char *argv[];
{
	extern int optind;
	extern char *optarg;
	int c;
	int status = 0;

	optind = 2;	/* Past the program name and the option letters. */
	while ((c = getopt(argc, argv, argv[1])) != EOF)
		switch (c) {
		case '?':
			status = 1;	/* getopt routine gave message */
			break;
		default:
			if (optarg != NULL)
				printf(" -%c %s", c, optarg);
			else
				printf(" -%c", c);
			break;
		}
	printf(" --");
	for (; optind < argc; optind++)
		printf(" %s", argv[optind]);
	printf("\n");
	exit(status);
}
-----
.TH GETOPT 1 local
.DA 12 April 1984
.SH NAME
getopt \- parse command options
.SH SYNOPSIS
.B set \-\- \`getopt
optstring
.B $*\`
.SH DESCRIPTION
.I Getopt
is used to break up options in command lines for easy parsing by
shell procedures, and to check for legal options.
.I Optstring
is a string of recognized option letters (see
.IR getopt (3));
if a letter is followed by a colon, the option
is expected to have an argument which may or may not be
separated from it by white space.
The special option
.B \-\-
is used to delimit the end of the options.
.I Getopt
will place
.B \-\-
in the arguments at the end of the options,
or recognize it if used explicitly.
The shell arguments
(\fB$1 $2\fR ...) are reset so that each option is
preceded by a
.B \-
and in its own shell argument;
each option argument is also in its own shell argument.
.SH EXAMPLE
The following code fragment shows how one might process the arguments
for a command that can take the options
.B a
and
.BR b ,
and the option
.BR o ,
which requires an argument.
.PP
.RS
.nf
set \-\- \`getopt abo: $*\`
if test $? != 0
then
	echo 'Usage: ...'
	exit 2
fi
for i
do
	case "$i"
	in
		\-a|\-b)
			flag=$i; shift;;
		\-o)
			oarg=$2; shift; shift;;
		\-\-)
			shift; break;;
	esac
done
.fi
.RE
.PP
This code will accept any of the following as equivalent:
.PP
.RS
.nf
cmd \-aoarg file file
cmd \-a \-o arg file file
cmd \-oarg -a file file
cmd \-a \-oarg \-\- file file
.RE
.PP
A program template similar to this example can be found in
.IR /usr/pub/template.sh .
.SH SEE ALSO
sh(1), getopt(3)
.SH DIAGNOSTICS
.I Getopt
prints an error message on the standard error output when it
encounters an option letter not included in
.IR optstring .
.SH HISTORY
Written by Henry Spencer, working from a Bell Labs manual page.
Behavior believed identical to the Bell version.
.SH BUGS
Whatever
.IR getopt (3)
has.
.PP
Arguments containing white space or imbedded shell metacharacters
generally will not survive intact;  this looks easy to fix but isn't.
.PP
The error message for an invalid option is identified as coming
from
.I getopt
rather than from the shell procedure containing the invocation
of
.IR getopt ;
this again is hard to fix.
.PP
The precise best way to use the
.I set
command to set the arguments without disrupting the value(s) of
shell options varies from one shell version to another.
-----
-- 
				Henry Spencer @ U of Toronto Zoology
				{allegra,ihnp4,linus,decvax}!utzoo!henry