tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Empty sub-shells and command groups in /bin/sh



The posix shell standard does not allow empty sub-shells, or command
groups.   That is, both
	( )
and
	{ }
(even if you write the latter as "{ ; }" though it turns out the ';'
there is not actually required, as it, or a \n, usually is before '}')
are both syntax errors.

NetBSD's shell accepts both currently (see PR bin/51145).

I am planning on (or considering) fixing that, and making both
be syntax errors.

I cannot imagine any normal usage being bothered by that, creating a
sub-shell, or a command list, and putting nothing in it is not a very
productive exercise - especially since both bash and dash generate
syntax errors for these (so it is unlikely that any of the zillions of
linux grown scripts will use that syntax either.)

However, most other shells (like NetBSD's) do not object.  zsh strangely
objects to the form with '( )' but not the '{ }' version.

The one case where I can see empty command lists being useful is in
function definitions.

That is, I know I like to write

	f() {
	}

and then sometime later, come back and fill in a body for the fuction.
Perhaps much later - you may have noticed a change I just made to one of
the sh tests which was for exactly this issue - there is a test planned
for which no code has yet been written, so it was just an empty function.
(Well, it contained a comment, but comments, and whitespace, are irrelevant
for this purpose.)

I have implemented a fix for PR bin/51145 but not yet committed it yet.
If desired, I believe (though have not yet actually done) make it so that
function bodies are an exception (an extension of the standard - we already
have that by also allowing a simple command as a function body, POSIX only
permits compound commands.)

That is, if people here think it worthwhile, then

	f() {
		# optional comments
	}

would remain accepted, whereas

	if true; then { } else ... fi

would not.    Note that to fix any bad usages, all that's needed is something
(more than comments and white space) inside the group, the obvious choice is
the ':' command

	( : )

is fine, as is

	{ :;}

(the semi-colon is required there, with or without a space after it.)

But other things are also possible

	(x=1)

(assign a variable a value, in a sub-shell, which means its value is
immediately lost again) or

	{ >&1; }

(redirect standard output onto itself)   Etc...

So, before I commit this fix (I have tested that a shell with it included
does build NetSD correctly. but so far not much beyond that) does anyone
have any opinions on the matter ?

kre

ps: various other places, beyond the one from PR bin/48489 (which is
fixed already I believe) where empty "commands" were permitted will also
get corrected by this fix.



Home | Main Index | Thread Index | Old Index