Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When I search for some process that doesn't exist, e.g.

$ ps aux | grep fnord                          
wayne    15745  0.0  0.0  13580   928 pts/6    S+   03:58   0:00 grep fnord

Obviously I don't care about grep - that makes as much sense as searching for the ps process!

How can I prevent grep from showing up in the results?

share|improve this question
If you need only the PID of a process, you can replace ps aux |grep with pgrep (or pgrep -f ). – jofel Apr 30 '13 at 13:54
Same question on Serverfault and Superuser. – Thor Apr 30 '13 at 14:08
is that output legit? it seems that there IS no program named fnord running... – acolyte Apr 30 '13 at 17:10
@acolyte, that's precisely it - but because it's piping the output into grep, grep is running (waiting for the output of ps aux, I expect). So the question is how to prevent grep fnord from showing up as a running process because obviously I'm not interested in that one. – Wayne Werner May 2 '13 at 1:58
@acolyte it's not a surprise that you cannot see the "fnord" line. You are not supposed to be able to see it. If you have some 2 or 3 minutes to spare, search for it. – Francesco May 2 '13 at 9:54

12 Answers 12

up vote 191 down vote accepted

Turns out there's a solution found in keychain.

$ ps aux | grep "[f]nord"

By putting the brackets around the letter and quotes around the string you search for the regex, which says, "Find the character 'f' followed by 'nord'."

But since you put the brackets in the pattern 'f' is now followed by ']', so grep won't show up in the results list. Neato!

share|improve this answer
@acolyte: The output from ps will include a line ending with grep [f]nord. However, that line will not make in through the grep filter, because the string [f]nord does not match the regular expression [f]nord. – LarsH Apr 30 '13 at 17:58
@LarsH interesting, thanks! i would have suggested ps aux | grep fnord | grep -v grep ...which seems to have already been suggested by a few people...lol – acolyte Apr 30 '13 at 18:16
This is a very old unix trick. I first saw it 15+ years or so ago. – slm May 1 '13 at 1:39
Grepping the output of ps may be an old trick, but it's unreliable. Use pgrep if available. – Gilles May 1 '13 at 22:19
@naxa Imagine you have a program call fnord and a program called safnorde. Or there's a user called bfnord, and you end up killing all his processes. Etc. – Gilles Nov 24 '13 at 22:37

Another option I use (especially just to look if a process is running) is the pgrep command. This will search for a matching process, but not list a grep line for the search. I like it because it is a quick way of search, without regexing or escaping anything.

pgrep fnord
share|improve this answer
They will want the -f option to be more like ps | grep. – jordanm Apr 30 '13 at 14:16
@jordanm Actually, pgrep -f will look more like ps -f | grep. – michelpm Apr 30 '13 at 18:09
There is also the -l argument to make it show the command that's being matched. – Patrick May 1 '13 at 3:34
ps | grep '[f]nord' is clever and venerable, but pgrep is right. – kojiro May 1 '13 at 11:33
You can always do ps $(pgrep cmd) ... if `pgrep is missing options (it won't work for empty set of commands though). – Maciej Piechotka May 1 '13 at 14:18

The ideal solution is the one presented by BriGuy

pgrep fnord 

But if you do not want to do that, you can just exclude all lines that matches with grep with:

ps aux | grep -v grep | grep "fnord"
share|improve this answer
but what if the line I'm looking for is "bash bash grep bash"? – Sparr Apr 30 '13 at 20:27
@Sparr Then you should use the best solution: pgrep or find another one ;) – RSFalcon7 May 1 '13 at 15:15
Watch out for the name length limit with pgrep. Use -f to get the full path name or you might find your matches fail with longer names. -l is nice too to list the matches – Neil McGill Dec 16 '14 at 14:32

In zsh, grep fnord =(ps aux).

The idea is, first run ps aux, put the result in a file, then use grep on that file. Only, we don't have a file, as we use zsh's "process substitution".

To illustrate, try

ps aux > ps.txt
grep fnord ps.txt
rm ps.txt

The result should be the same.

General comment on some of the other answers. Some are far to complicated and/or long to type. It is not only a matter of being right, it should be usable as well. But that doesn't mean some of those solutions are bad; only, they must be wrapped within a mini-UI to make them usable.

share|improve this answer
Not knowing zsh's process substitution, but is it certain that the two processes are called one after the other and not in parallel? – Paŭlo Ebermann May 1 '13 at 10:17
@PaŭloEbermann: For parallel is the <(command). grep grep =(ps aux) doesn't show any line. – Maciej Piechotka May 1 '13 at 14:17

Not the most elegant solution but you could do this:

$ ps aux | grep fnord | grep -v grep

share|improve this answer
ps aux | grep $(echo fnord | sed "s/^\(.\)/[\1]/g")
share|improve this answer
this looks like an IOCCC, but for unix command line instead of C ^^ Just | grep $(echo fnord) wasn't enough ? you also ask sed to search and replace each char in "fnord" by its own value? ^^ congrats. I bet I can do an even longer one, but it probably won't be as funny ^^ – Olivier Dulac Apr 30 '13 at 16:26
I apologize as the tone of my above comment may sound offensive (and I can't edit it after 5mn)... Your answer was really a joyful read, and I wasn't trying to make you look bad. I really think you did it like this on purpose ^^ – Olivier Dulac Apr 30 '13 at 16:31
Don't apologize, your answer was really fun to read (and spot-on right too). I meant pgrep -l $1 anyway ;) – philipyassin Apr 30 '13 at 16:48
@OlivierDulac: He doesn't just replace the first char with its own value; he replaces it with the concatenation of its value among square brackets. (Those square brackets are not special, they're literal.) Basically, he's generalizing on Wayne Werner's answer, so that the process of putting square brackets around the first character can be scripted. +1 – LarsH Apr 30 '13 at 18:02
ps aux | grep '[^]]fnord' would avoid that gymnastic. – Stéphane Chazelas Apr 30 '13 at 20:21

The simplest shell-agnostic way to do this would be to store it in a variable first:

PS_OUTPUT="$(ps aux)"; echo "$PS_OUTPUT" |grep fnord

Call-out: @EmanuelBerg's grep fnord =(ps aux) answer is by far the most elegant, though it requires zsh. I briefly had it in my rc files, but bash complains about that syntax even despite a conditional that should prevent its evaluation.

From my rc files, I have a case-insensitive version that takes grep's args:

psl() {
  local PS_OUTPUT="$(ps auxww)"
  echo "${PS_OUTPUT%%$'\n'*}" >&2  # title, in stderr to avoid pipes
  echo "${PS_OUTPUT#*$'\n'}" |grep -i "${@:-^}"

Code walk, one bullet per line of code:

  • Capture the verbose ps output (in a local variable so it goes away when the function completes).
  • Display the first line (the title) in standard error so the results can be further filtered without affecting the title. The substitution says: take $PS_OUTPUT and remove everything after the first line feed (regex equiv: s/\n.*$//msg). This prevents us from grepping the title.
  • Display the ps output with everything except the first line (regex equiv: s/^.*\n//m) and grep its contents with -i for case-insensitive and with all of the arguments handed this function, or, in the case of no arguments, ^, (match the start of any line, which matches everything).
share|improve this answer

My answer is a variation on the typical answer for searching for "foobar" in a 'ps' listing. The argument of "-A" "ps" is more portable than "aux", I believe, but this change is irrelevant to the answer. The typical answer looks like this:

$ ps -A -ww | grep [f]oobar

Instead I use this pattern:

$ ps -A -ww | grep [^]]foobar

The main advantage is that it's easier to write scripts based on this patterns because you simply concatenate a static string "[^]]" with whatever pattern you are looking for. You don't need to strip off the first letter of the string then insert it between the square braces and then concatenate the that back together again. When scripting in shell it's easier to simply stick "[^]]" in front of the pattern you were lookginfor looking for. String slicing in Bash is an ugly thing, so my variation avoids that. This variation says show the lines where the pattern matches WITHOUT a leading right-square-bracket ]. Since the search pattern to exclude a square bracket actually adds the square bracket to the pattern then it will never match itself.

So you could write a portable 'psgrep' command as follows. Here, I make some allowance for differences between Linux, OS X BSD, and others. This adds the column headers from 'ps', provides a more custom 'ps' format that suits my needs betters, and displays processes listing extra, extra wide so that none of the command-line arguments are missed. Well, most are not missed. Java being Java, it often does things in the worst possible way, so you some java services will run past the maximum allowed length of arguments that the process table will keep track of. I believe this is 1024 characters. The command-lone length allowed to start a process is much longer, but the kernel process table doesn't bother to keep track of anything over 1K in length. Once the command is started the command-name and argument list isn't needed against, so what gets stored in the process table is just informational.

psgrep ()
    case "$(uname -s)" in
            ps -A -ww -o pid,ppid,nice,pri,pcpu,pmem,etime,user,wchan,stat,command | grep -i -e "^[[:space:]]*PID" -e ${pattern}
            ps -A -ww -o pid,ppid,tid,nice,pri,pcpu,pmem,etime,user,wchan:20,stat,command | grep -i -e "^[[:space:]]*PID" -e ${pattern}
        *)  # other UNIX flavors get a minimalist version.
            ps -A -ww | grep -i -e ${pattern}
share|improve this answer

Maybe time to use a real sequence this time. The use of pipes makes it parallel.

ps aux >f && grep tmpfs <f

Ugly because there will be a file f, but it's not my fault that there is no syntax for sequential processes where you still want to use the output of a previously run process.

Suggestion for the syntax of a sequential operator:

ps aux ||| grep tmpfs
share|improve this answer
The inability of the common people to easily filter a stream is hardly a reason for the elite to base themselves with sequences. It would be a step backward in computing. – A-B-B Aug 18 '14 at 20:27
@A-B-B en.wikipedia.org/wiki/Communicating_sequential_processes have many more operators than those that ended up in the Thompson shell. There could just have been an operator that is sequential, and which communicated its result to the next process in the sequence as soon as its exits. A "step backward in computing" by providing an additional operator seems a bit harsh. – Anne van Rossum Aug 19 '14 at 7:09
Nice link, but of course sequential processing is worse in both CPU and memory (or disk) use -- relative to parallel processing. In this instance, if I must first store all ps output before I grep, I'm using more memory (or disk) for longer. – A-B-B Aug 19 '14 at 19:37

The pgrep command, as others have stated, will return the PID (process ID) of processes based on name and other attributes. For example,

pgrep -d, -u <username> <string>

will give you the PIDs, delimited by a comma (,) of all processes whose name matches being run by user <username>. You can use the -x switch before to return only exact matches.

If you want to get more information about these processes (as running the aux options from ps implies), you can use the -p option with ps, which matches based on PID. So, for example,

ps up $(pgrep -d, -u <username> <string>)

will give detailed information of all the PIDs matched by the pgrep command.

share|improve this answer
ps fails if pgrep returns an empty set. I have an answer which builds upon yours and tries to address this issue. – A-B-B Aug 19 '14 at 17:00

Here is a simple example to find PID of ssh-agent for username without showing PID of grep process itself:

ps xu | grep "${USER}.*[ ]/usr/bin/ssh-agent" | awk '{print $1 $2;}'

If you want for example to kill ssh-agent for current user you might use following command:

kill `ps xu | grep "${USER}.*[ ]/usr/bin/ssh-agent" | awk '{print $2;}'`

To create a handy alias add to your ~/.bashrc or ~/.zshrc file the following code:

function function1 () {
    ps xu | grep "$1.*$2" | awk '{print $1" "$2" "$11;}'
alias mygrep="function1"

And to use alias here are examples to force everyone to learn regular expressions:

. /etc/profile #to make alias usable
mygrep ${USER} ${PROCESS_PATH}
mygrep ${USER} "[f]nord"
mygrep "[f]nord"
mygrep ".*[s]shd"

P.S. I've only tested these commands on Ubuntu and Gentoo.

share|improve this answer
(1) The question doesn't say that the user is looking for one of his own processes — the user might not know the owner of the process he's looking for.  (2) As fancy as this answer is, it would still fail if you had said "${USER}.* /usr/bin/ssh-agent".  It works because you said [ ]; i.e., you are just using the mechanism of the accepted answer.  You might as well just grep "[s]sh-agent". – G-Man Nov 6 '15 at 14:27
You are right. (1) I shared what might be useful as I found myself facing this page once in a while (2) Yes I used regular expression as in accepted answer. (3) I updated my answer to be the same as accepted as the one is better, but I also showed how to make and alias to be used with username provided or without it. (4) Also shown how to define function, though it is not necessary but works in interesting way as $1 and $2 doesn't overlap. Thx #G-Man – Constantin Zagorsky Nov 7 '15 at 16:30

You can do it easily, just with defining an ALIAS in your .bashrc like this:

alias grep='grep -v grep | grep'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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