Using getopt to parse multi-argument options

Daniel R. Levy levy at ttrdc.UUCP
Wed Jan 18 13:48:13 AEST 1989


In article <1989Jan16.023712.29002 at utzoo.uucp>, henry at utzoo.uucp (Henry Spencer) writes:
> In article <3652 at phri.UUCP> roy at phri.UUCP (Roy Smith) writes:
> >	I'm writing a program which will take an optional range, in the
> >style of graph(1)'s "-x xmin xmax".  How do I tell getopt to parse
> >something like that? ...
> 
> You can't.  The only getopt-compatible way is to require the user to
> say "-x 'xmin xmax'" instead, and have your code pull the single argument
> apart.  This is what the AT&T syntax standard mandates (with the further
> flourish that tabs and commas must work as separators, not just spaces,
> as I recall).

Actually, what Roy had in mind IS possible.  Yes it violates the syntax
standard, but if one is masochistic enough to WANT that, it's doable through
suitable abuse of optind.  This permits argument sequences of the form
"-x <xmin> <xmax>" or even "-bundledoptionlettersx<xmin> <xmax>" for the
truly warped of mind:

main(argc,argv)
char **argv;
{
	...
	int c;
	extern char *optarg;
	extern int optind;
	double xmin, xmax, atof();
	void exit(), usage();
	...

	while ((c=getopt(argc,argv,"x:abcdefgh")) != EOF) {
		switch(c) {
		case 'a':	/* ordinary options */
		...
		case 'h':	/* etc. */
		case 'x':	if (optind == argc || !isanumber(optarg) ||
					!isanumber(argv[optind]) {
					usage();
					exit(1);
				} else {
					xmin=atof(optarg);
					xmax=atof(argv[optind]);
					optind++; /* skip the next argument */
				}
				break;
		...
		}
	}
	...
}

This will only work for compiled code; I know of no way that getopt(1) can
be made to do something similar in a shell script.
-- 
Daniel R. Levy             UNIX(R) mail:  att!ttbcad!levy
AT&T Bell Laboratories
5555 West Touhy Avenue     Any opinions expressed in the message above are
Skokie, Illinois  60077    mine, and not necessarily AT&T's.



More information about the Comp.lang.c mailing list