1
#! /bin/bash

func1()
{
        echo $$
}

echo $$
( func1 )

This gives the result:

9644
9644

I expected that they would be different. Can anyone please explain why they are not?

David Buck
  • 3,752
  • 35
  • 31
  • 35
yi.chen
  • 13
  • 3
  • 1
    Does this answer your question? [Get pid of current subshell](https://stackoverflow.com/questions/20725925/get-pid-of-current-subshell) – David Buck Mar 09 '20 at 13:11
  • This is mandated by POSIX, presumably for uniformity since a shell isn't required to create a new process for a subshell. – chepner Mar 09 '20 at 13:15

1 Answers1

2

From the section PARAMETER EXPANSION of man bash:

$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.

This is also mandated by the POSIX shell specification:

$ 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.

If you want the process ID of the subshell, use $BASHPID:

func1() { echo $BASHPID; }
echo $BASHPID
28365
( func1 )
28627
chepner
  • 497,756
  • 71
  • 530
  • 681
oliv
  • 12,690
  • 25
  • 45