What does grep -v "grep" mean and do?

grep -v "grep" takes input line by line, and outputs only the lines in which grep does not appear. Without -v, it would output only the lines in which grep does appear. See man grep for details.

As far as the grep utility is itself concerned, it's unimportant that the pattern grep passed to it as an argument is the same as its name. But in most cases where grep -v grep actually appears, this is no coincidence.

grep -v grep (or grep -v 'grep' or grep -v "grep") often appears on the right side of a pipe whose left side is a ps command. That is likely where you have seen it. For example, I might be looking for running programs whose names, paths, or command-line arguments suggest they're related to Xfce:

ek@Io:~$ ps x | grep xfce
 2955 ?        Ssl    0:10 xfce4-power-manager
 2958 ?        S      0:00 /usr/lib/x86_64-linux-gnu/xfce4/xfconf/xfconfd
31901 pts/1    S+     0:00 grep --color=auto xfce

My grep command was shown in the output, but it's not what I'm looking for. I'm looking for information on processes that were already running when I examined what was running, not the process that's only running because of my effort to examine what is running.

One common way to remove this distraction is to add another pipe to grep -v grep:

ek@Io:~$ ps x | grep xfce | grep -v grep
 2955 ?        Ssl    0:10 xfce4-power-manager
 2958 ?        S      0:00 /usr/lib/x86_64-linux-gnu/xfce4/xfconf/xfconfd

grep without -F treats its pattern as a regular expression rather than a fixed string. So another approach is to write a regular expression that matches exactly xfce but is written differently. For example:

ek@Io:~$ ps x | grep '[x]fce'
 2955 ?        Ssl    0:10 xfce4-power-manager
 2958 ?        S      0:00 /usr/lib/x86_64-linux-gnu/xfce4/xfconf/xfconfd

This works because [x] is a character class that matches exactly the letter x.


One shortcoming of those popular methods is that they'll filter out lines that contain grep even when they're not the grep command you just ran yourself. They might not even be grep commands--just commands whose names, paths, or command-line arguments contain grep. So, as Sergiy Kolodyazhnyy has pointed out, often neither of those ways (nor any other approach involving piping the output of ps) is really ideal and, as Nic Hartley mentioned, other ways often use pgrep. For example:

ek@Io:~$ pgrep -af xfce
2955 xfce4-power-manager
2958 /usr/lib/x86_64-linux-gnu/xfce4/xfconf/xfconfd
  • -a shows the full command line. Omit it to show only the process ID number.
  • -f searches in full command line. Omit it to search only the names.

grep --help tells us what -v flag does:

-v, --invert-match        select non-matching lines

You can use -v flag to print inverts the match; that is, it matches only those lines that do not contain the given word. For example print all line that do not contain the word bar:

$ grep -v bar /path/to/file

(read more...)

Tags:

Bash

Grep