2

In my shell scripts,I wrote those:

#! /bin/bash
(ls;echo$$)
echo$$

then I run the shell,the two output is the same

2592
2592

why subshell didn't have a new process id?

storen
  • 1,025
  • 10
  • 22

1 Answers1

3

$$ is the process ID of the main shell. To get the process ID of a subshell, use BASHPID:

$ echo $$ $BASHPID; ( echo $$ $BASHPID; )
19610 19610
19610 21937

The subshell has PID 21937.

Documentation

From man bash:

BASHPID
Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as sub‐ shells that do not require bash to be re-initialized.

By contrast, $$ is documented as follows:

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

John1024
  • 109,961
  • 14
  • 137
  • 171