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?

0
2

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

    ps -ef | grep [s]shd
1
  • perfect as I can use this with variables as well. – devnull Jul 27 '15 at 10:35
6

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

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.

0
3

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.

0
2

What you need is ps -e | grep sshd

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

2
ps -fCsshd

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

-1

You can use grep itself to avoid that result:

ps -ef|grep your_search_chain|grep -v grep

1
  • 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".

1
  • This answer has already been given by fd0, please don't duplicate. – YoMismo Jul 27 '15 at 10:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.