How to get the process id of a bash subprocess on command line
bash, macos, process, shell, unix
Solution
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:
echo $$; ( F='/tmp/myps'; [ ! -f $F ] && echo 'echo $PPID' > $F; )
It prints:
5642
13715
Where 13715 is the pid of the subshell. To test this when I do:
echo $$; ( F='/tmp/myps'; [ ! -f $F ] && echo 'echo $PPID' > $F; bash $F; ps; )
I get this:
5642
13773
PID TT STAT TIME COMMAND
5642 s001 S 0:02.07 -bash
13773 s001 S+ 0:00.00 -bash
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.
Problem
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.