1
# ps -ef | grep gre
root     15067 63614  0 11:03 pts/0    00:00:00 grep --color=auto gre

Another example

# ps -ef | grep sshd
root      1186     1  0 Jul26 ?        00:00:00 /usr/sbin/sshd -D
root     15439 63614  0 11:05 pts/0    00:00:00 grep --color=auto sshd

How can I stop the grep command being found by itself and not returned as a field?

8 Answers8

6

The better way is to use pgrep for that task. It seems to be available on most systems these days.

Satō Katsura
  • 13,368
  • 2
  • 31
  • 50
3

There are a number of ways, more or less hacky and awkward. My favourite is to insert a double-backslash before a letter in my search string:

ps -ef | grep ss\\hd

The \\ is interpreted to \ by the shell, and \h is interpreted as equivalent to 'h' by grep. So it is effectively searching for 'sshd' as before. However, its own command string no longer contains 'sshd', it contains 'ss\hd', so it doesn't match itself.

2

Change the pattern so it is a regular expression that will not match the literal text.

    ps -ef | grep [s]shd
fd0
  • 1,449
2

When available, just use pgrep which was designed to properly overcome this issue, eg:

ps -f $(pgrep sshd)

This method is cleaner than the hackish workarounds usually suggested.

jlliagre
  • 61,204
2

What you need is ps -e | grep sshd

(ps -ef is listing processes and their arguments, ps -e lists only the processes).

Emmanuel
  • 4,187
2
ps -fCsshd

That's probably all you need on a linux system.

mikeserv
  • 58,310
-1

You can use grep itself to avoid that result:

ps -ef|grep your_search_chain|grep -v grep

YoMismo
  • 4,015
  • This is not the correct way to do, and it may lead to false positives if the line containing "your_search_chain" also contains "grep". – Adrien M. Jul 27 '15 at 10:21
-1

In the same way as Andrew, you can use [] :

ps -ef |grep [s]shd

It will be taken as a simple BRE regex, and will not match itself. I consider it less intrusive than the backslashes, for which you'll have to care about "what interpreter will take them into account first".

Adrien M.
  • 3,566