I know in bash we can create subshells using round parenthesis ( and ). As per bash man page:
(list) list is executed in a subshell environment
Also to get the current process id we use:
echo $$
Now my question is how to get process id of a subshell created using ( and ) on command line?
If I use this:
echo $$; ( echo $$; )
I will get the parent shell’s process id printed twice on stdout since $$ gets expanded even before subshell is created. So how to really force the lazy expansion?
[Solution should work on Mac as well not just Linux]
Update:
Suggested linked answer doesn’t work since echo $BASHPID does not work on my Mac and returns blank.
Thanks to all of you for spending your valuable time in finding answer to my question here.
However I am now answering my own question since I’ve found a hack way to get this pid on bash ver < 4 (will work on all the versions though). Here is the command:
It prints:
Where 13715 is the pid of the subshell. To test this when I do:
I get this:
Telling me that 13773 is indeed the pid of the subshell.
Note: I reverted back to my original solution since as @ChrisDodd commented that
echo $$; ( bash -c 'echo $PPID'; )doesn’t work Linux. Above solution of mine works both on Mac and Linux.