17

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 ?

0

1 Answer 1

22

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.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .