0

In my Bash shell the $$ variable expands to the process ID of the shell.

So why does ps print its own name when I execute this?

$ bash -c 'ps -p $$ -o comm='
ps

When I follow it with a no-op command, ps does print the name of the shell.

$ bash -c 'ps -p $$ -o comm= && true'
bash

Versions:

  • GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)
  • ps from procps-ng 3.3.16
  • Why bash does not spawn a subshell for simple comamands? is another way of asking the same question. Sergiy Kolodyazhnyy shows that the first example is a performance optimization on a simple command. I expected Bash to fork a new process, but instead it starts a process with the same pid and replaces itself. The second example is a compound command. Bash can't replace itself because it needs to supervise all the commands in the compound, so it forks each subprocess with a new pid and retains its own. – Iain Samuel McLean Elder Aug 31 '23 at 12:47
  • In particular, Bash needs to keep itself alive until ps exits so it can then run true if needed. It wouldn't need to keep itself alive until true exits, though, but Bash only optimizes the case of a single command, not any tail-end command. However, ksh93 optimizes that too, e.g. ksh -c 'ps -p $$ -o comm=; ps -p $$ -o comm=' prints ksh, ps – ilkkachu Aug 31 '23 at 17:11

0 Answers0