The value of $$
in bash
will stay the same even if you're examining it in a subshell. This behavior is mandated by the POSIX standard:
$
Expands to the decimal process ID of the invoked shell. In a subshell [...], $
shall expand to the same value as that of the current shell.
You should probably be using $BASHPID
instead. The following is from the bash
manual:
BASHPID
Expands to the process ID of the current bash process. This
differs from $$
under certain circumstances, such as subshells
that do not require bash to be re-initialized. Assignments to
BASHPID
have no effect. If BASHPID
is unset, it loses its
special properties, even if it is subsequently reset.
Rewriting your code to use $BASHPID
instead:
printf '%s\n' "$BASHPID"
true | while true; do
printf '%s\n' "$BASHPID"
break
done
Running this will output two different PIDs.