user10158754
user10158754

Reputation:

Why does "pgrep -f bash" emit two numbers instead of one?

When I run this script in shell:

printf "Current bash PID is `pgrep -f bash`\n"

using this command:

$ bash script.sh

I get back this output:

Current bash PID is 5430
24390

Every time I run it, I get a different number:

Current bash PID is 5430
24415

Where is the second line coming from?

Upvotes: 0

Views: 436

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295363

When you use backticks (or the more modern $(...) syntax for command substitution), you create a subshell. That's a fork()ed-off, independent copy of the shell process which has its own PID, so pgrep finds two separate copies of the shell. (Moreover, pgrep can be finding copies of bash running on the system completely unrelated to the script at hand).


If you want to find the PID of the current copy of bash, you can just look it up directly (printf is better practice than echo when contents can contain backslashes or if the behavior of echo -n or the nonstandard bash extension echo -e is needed, but neither of those things is the case here, so echo is fine):

echo "Current bash PID is $$"

Note that even when executed in a subshell, $$ expands to the PID of the parent shell. With bash 4.0 or newer, you can use $BASHPID to look up the current PID even in a subshell.


See the related question Bash - Two processes for one script

Upvotes: 3

Related Questions