[mod.os.unix] getopt command problem: doesn't re-quote

usenet@mcdchg.UUCP (03/13/87)

Don't know if anyone's brought this up before, but the getopt command seems to 
have a bit of a problem.  It doesn't "re-quote" arguments, so they get broken
up incorrectly when parsed by the shell.  

Example:	 getopt x: -x "a test"
produces:	-x a test --
instead of:	-x "a test" --
Resulting in:  			Instead of:
		$1=-x 			$1=-x
		$2=a 			$2=a test
		$3=test 		$3=--
		$4=--

Even "sh" itself recognizes this problem, and provides re-quoting via "$@" .

Since writing one's own getopt program is trivial on a system with the getopt
call, this is more of a major annoyance than a problem.  So, my questions:
1)  Any portable workarounds (I can't think of any)?
2)  Have any of the standards groups thought of proposing that this be fixed?

usenet@mcdchg.UUCP (03/25/87)

The way getopt is intented to be called, re-quoting would not work.
Getopt is supposed to be invoked as:

	set -- `getopt string $*`

If getopt were to place quotes around arguments containing spaces,
these arguments would still be broken up.  In the first place, they
would be broken up before being passed to getopt.  In the second
place, if this were avoided they would be broken up after getopt
returned.

The solution is to change the way getopt is called to

	eval "set -- `getopt string "$@"`"

Then getopt should be changed to quote not only spaces, but also
other characters special to the shell, such as "$" and "*".  This
quoting should be done by preceding the special characters with
backslashes.

This solution requires that all shell procedures that use getopt
be changed.  Of course these programs fail now on arguments con-
taining white space, but if they are not changed when getopt is
they will fail on arguments containing *any* characters that are
special to the shell.
				Kenneth Almquist

usenet@mcdchg.UUCP (03/25/87)

< Since writing one's own getopt program is trivial on a system with the
< getopt call, this is more of a major annoyance than a problem.  So, my
< questions:
< 1)  Any portable workarounds (I can't think of any)?
< 2)  Have any of the standards groups thought of proposing that this be
< fixed?

Both System V release 3 and POSIX (1003.2) recognize this problem. The Vr3
solution was to introduce a builtin into the shell called getopts which
would replace the use of getopt and do all of the proper quoting. POSIX is
following suit.

					Tony Hansen
					ihnp4!pegasus!hansen