linuxbashshell

Why is the PID and PPID of subshell same as that of the main shell?


The old.sh file contains the following code:

#!/bin/bash
echo $$
echo $PPID
(
        echo $$
        echo $PPID
)

bash /tmp/new.sh

The /tmp/new.sh file contains the following:

#!/bin/bash
echo $$
echo $PPID

When I run the old.sh file, this is the result:

632
143
632 # PID of subshell
143 # PPID of subshell
634
632

I expected that the PPID of the subshell would be equal to the PID of the main shell. However, the PID and PPID of the subshell and the main shell are the same.

Please explain why.


Solution

  • From https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :

    $ Expands to the decimal process ID of the invoked shell. In a subshell (see Shell Execution Environment ), '$' shall expand to the same value as that of the current shell.

    It is specified to do that.

    If you want the real pid, use $BASHPID.