I ran following code :
echo $$ # Output : 3911 true | while true; do eval 'echo $$' break done # Output : 3911
The documentation says that while loop (involved in pipe) runs in a subprocess, in that case, should the two process ids be different ?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
The value of
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
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
BASHPIDhave no effect. If
BASHPIDis unset, it loses its special properties, even if it is subsequently reset.
Rewriting your code to use
printf '%s\n' "$BASHPID" true | while true; do printf '%s\n' "$BASHPID" break done
Running this will output two different PIDs.