Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between pgrep in sh and bash

Tags:

grep

bash

sh

Here is a test:

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

Why is pgrep giving output when run from sh? (As far as I can see, there are no processes on my computer that is named novalidname)

like image 868
Håkon Hægland Avatar asked Aug 02 '15 14:08

Håkon Hægland


2 Answers

It's probably a timing issue and pgrep finds itself, as you're issuing it with -f and novalidname is present in the command line. Try with -l to confirm.

like image 124
mustaccio Avatar answered Sep 29 '22 01:09

mustaccio


The actual explanation:

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

  2. If you execute bash -c with a simple command, then bash will exec the command rather than creating a redundant subshell to execute it in. Consequently, bash -c "pgrep -f blah" will replace the bash process with a pgrep process. If that pgrep process is the only process whose command line includes blah, then pgrep will not display any PIDs (as per 1).

  3. dash does not perform the above optimization. (zsh and ksh do.) So if on your system, sh is implemented with dash, then sh -c "pgrep -f blah" will result in two processes being executed -- the sh process and the pgrep child -- both of which contain blah in their command lines. pgrep will not report itself, but it will report its parent.

like image 39
rici Avatar answered Sep 29 '22 01:09

rici