3
votes

I am learning bash-shell by Advanced Bash-Scripting Guide. This book says

A listing of commands within parentheses starts a subshell.

So, I tried this code:

echo "in parentshell \$\$=$$"
( echo "in subshell \$\$=$$" )

The latter should print the pid of the sub-process I think, but in fact the result is just the same as pid of the parent shell. Can anyone tell me why?

1

1 Answers

3
votes

According to the Special Parameters section of the reference manual,

$$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the invoking shell, not the subshell.

So there's nothing strange about the behavior you observe, it's fully documented.

As Ansgar Wiechers rightly observes in a comment,

The PID of the subshell can be determined with the variable $BASHPID.

The documentation of this will be found in the Bash Variables section of the reference manual. There you'll read:

BASHPID expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized.

Thanks Ansgar!

Note. I don't really like the reference you're reading.