Why does ps output show a process even if it is not running?

And this is why you shouldn't grep or otherwise parse the output of ps for matching commands, but use tools like pgrep and pidof.

When you run ps | grep foo, the grep foo process is also listed by ps - therefore grep foo matches itself along with any other foo processes. The exact same thing happens when you do echo $(ps aux | awk '/firefox/...) - the awk command matches itself.

Indeed, depending on what output you want from ps, you might be better off using pgrep's output with ps. For example, the states of all Google Chrome processes in my system:

ps -p $(pgrep -d, chrome) -o pid,state

pgrep's flexibility in this regard is very useful - note how I can specify an output delimiter with -d, then use it as PID list argument to ps. pgrep and pkill are also capable of reading from a PID file.


As muru already pointed out grep leaves trace of itself in the ps, however, there is a small workaround for using grep with ps : use double quotes and brackets on the first letter like so ps aux | grep "[f]irefox" (Source: https://unix.stackexchange.com/a/74186/85039).