Difference between pgrep in sh and bash

Here is the test:

$ bash -c "pgrep -f novalidname" $ sh -c "pgrep -f novalidname" 11202 

Why does pgrep give output on startup from sh ? (As far as I see, there are no processes on my computer named novalidname )

+4
source share
3 answers

There is probably a problem with synchronization and pgrep , as you issue it with -f and novalidname , which is present on the command line. Try -l confirm.

+5
source

Actual explanation:

  • Regardless of flags, pgrep never returns its own PID.

  • If you run bash -c with a simple command, then bash will be exec for this command instead of creating an extra subshell to execute it. Therefore, bash -c "pgrep -f blah" will replace the bash process with the pgrep process. If this pgrep process is the only process that has blah on the command line, then pgrep will not display the PID (as per 1).

  • dash does not perform the above optimization. ( zsh and ksh do.) So, if sh is implemented using dash on your system, then sh -c "pgrep -f blah" will lead to the execution of two processes - the process sh and pgrep child - both of them contain blah in their command lines . pgrep will not report about itself, but will report about its parent.

+2
source

This one thing (being due to delay) also sees:

 $ ps ax | grep novalidname 

Here it also shows. (on Ubuntu does for me. (under bash)

Another thing is that related to / bin / sh?

Most Linux / bin / sh distributions have a soft link to the default shell, which is usually actually bash, but can be any other shell.

The temporary difference causing grep / pgrep to display can be entered by looking for the location of the soft link (hm, odd) or some other shell related to / bin / sh, which runs slightly different than bash, which results in the delay required for the process to display in pgrep.

In addition, bash will first try to load the source ~ / .bashrc and load its history, and / bin / sh will do whatever it takes. In .bashrc, pgrep can be defined as an alias in another way, which can also affect the difference.

To see where / bin / sh points to:

 $ readlink -e /bin/sh 

Or just run sh to see what will be displayed .: D

+1
source

All Articles