Subject: Re: correct shell behaviour?
To: David Laight <>
From: Greg A. Woods <>
List: tech-userlevel
Date: 08/11/2002 13:12:44
[ On Thursday, August 8, 2002 at 14:52:06 (+0100), David Laight wrote: ]
> Subject: correct shell behaviour?
> What should sh output for the following:
> (exit 3);echo $? $(echo $?) $?
> In particular, when the last $? is expanded, is the 'last pipeline'
> the '(exit 3)' or '$(echo $?)'.

Before I read the other replies and confuse myself I'm going to reply
directly and say that I believe the final '$?' should expand to '3'
since the most recent command list is '(exit 3)'.  It is my
understanding that command-line substitution does not count as a

The wording in the pdksh manual doesn't help though...

SuSv2 says nothing about the exit status of a list run in a command
substitution expansion and by implication one must assume it is
discarded (since everywhere else the disposition of the exit status is
explicitly documented).

Unfortunately (from my perspective) SunOS-5 (and no doubt all
implementations of KSH and of the UNIX /bin/sh) disagrees with both
shells on NetBSD, and with my interpretation:

	12:55 [126] $ (exit 3);echo $? $(echo $?) $?
	3 3 0
	12:55 [127] $ sh
	$ (exit 3);echo $? `echo $?` $?
	3 3 0

POSIX 1003.2 (Draft 11.2) comes close to giving an example, but it's
missing the very last part:

       sleep 1000&
       kill -kill $pid
       wait $pid
       echo $pid was terminated by a SIG$(kill -l $?) signal.

Obviously the '$?' in the command substitution is expected to have the
value it would have outside in the same command, i.e. if the last
command were as follows then the same value should be printed twice:

	echo $? (echo $?)

So would expect NetBSD's /bin/ksh to be correct, though it differs from
SunOS-5 in regard to the final '$?'

Our /bin/sh is definitely broken for the second '$?' though, and it too
differs from SunOS-5 for the final one.  Interestingly it was not broken
in 1.3.3 (and presumably was OK in earlier releases too).

Perhaps in the lack of explicit documentation in the standards we've got
to resort to compatability with the historical implementations.

								Greg A. Woods

+1 416 218-0098;            <>;           <>
Planix, Inc. <>; VE3TCP; Secrets of the Weird <>