Subshells and PIDs: Why do $$ and \$\$ sometimes match under nested sh -c?
I know this is an artificially complicated example, but why are both PIDs the same in the first line, while (as expected, to me at least) the two other lines yield different PIDs?
$ sh -c 'sh -c "echo $$ \$\$"'
4500 4500
$ sh -c 'sh -c "echo $$ \$\$"; true'
4596 5060
$ sh -c 'tru开发者_开发知识库e; sh -c "echo $$ \$\$"'
4728 2868
Thanks!
For me in bash 4.1.5, the output of first line is:
sh -c 'sh -c "echo $$ \$\$"'
4063 4064
as expected - values are different. Also tested on ash, sh, and zsh.
It must be some tricky optimization.
Update:
in bash 3.2 there is and "ONESHOT" feature: see comment in the shell.c:1243:
#if defined (ONESHOT)
/* Run one command, given as the argument to the -c option. Tell
parse_and_execute not to fork for a simple command. */
精彩评论