How to get the process id of a bash subprocess on command line

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)