[comp.unix.shell] How does a shell know if it's in the foreground or the background?

lewis@tramp.colorado.edu (LEWIS WILLIAM M JR) (05/02/91)

Guy Harris (auspex!guy@uunet.UU.NET) was kind enough to send me the following:

...
> BTW, your script didn't work when I tried it under a version of the
> Bourne shell that *doesn't* support job control; I put:
> 
> 	if [ "$$" -eq "$!" ]
> 	then
> 		echo background
> 	else
> 		echo foreground
> 	fi
> 
> in a file "/tmp/scripto":, made it publicly-executable, fired up a
> Bourne shell, and did
> 
> 	/tmp/scripto
> 
> and then
> 
> 	/tmp/scripto&
> 
> With no other background jobs running, it printed "foreground" in both
> cases.
> 
> The Bourne shell manual page says:
> 
>      The following parameters are automatically set by the shell:
> 
>           $    The process number of this shell.
>           !    The process number of the last background  command
>                invoked.                  ^^^^
> 
> so it would appear that the only way the test could succeed would be if
> the shell executing the test was also the last background command run by
> the shell itself, which seems *quite* unlikely.... [My emphasis]

Sorry if I misled anyone.  As usual, every word on the manual page counts.