Dhiren Dash
Dhiren Dash

Reputation: 111

UNIX grep command (grep -v grep)

I was going through something and found this which I could not understand,

grep -v grep

What does this signify? I know that -v switch will select all the lines that do not match. But why the second grep?

This is the full command:

ps -ef | grep rsync -avz \
| grep oradata${DAY}_[0-1][0-9] \
| grep -v grep \
| awk '{print $2}' | wc -l

Upvotes: 4

Views: 9548

Answers (1)

Amit
Amit

Reputation: 20456

grep when used with ps -ef also outputs the grep used for filtering the output of ps -ef.

grep -v grep means that do not include the grep used for filtering in the command output.

You can also avoid grep in the results by using a regex pattern. For example, in the following example you won't need a grep -v grep to avoid grep in the output:

ps -ef | grep [r]sync

Here's another example, showing different commands and their output, notice the first one where grep is also in the output whereas in the last two grep is not printed in the output:

$ ps -ef | grep ipython
  501 18055 18031   0 12:44AM ttys000    0:00.00 /bin/bash /Users/amit/anaconda/bin/python.app /Users/amit/anaconda/bin/ipython notebook --profile=ocean
  501 18056 18055   0 12:44AM ttys000    0:00.85 /Users/amit/anaconda/python.app/Contents/MacOS/python /Users/amit/anaconda/bin/ipython notebook --profile=ocean
  501 18067 18031   0 12:44AM ttys000    0:00.00 grep ipython

$ ps -ef | grep ipython | grep -v grep
  501 18055 18031   0 12:44AM ttys000    0:00.00 /bin/bash /Users/amit/anaconda/bin/python.app /Users/amit/anaconda/bin/ipython notebook --profile=ocean
  501 18056 18055   0 12:44AM ttys000    0:00.85 /Users/amit/anaconda/python.app/Contents/MacOS/python /Users/amit/anaconda/bin/ipython notebook --profile=ocean

$ ps -ef | grep [i]python
  501 18055 18031   0 12:44AM ttys000    0:00.00 /bin/bash /Users/amit/anaconda/bin/python.app /Users/amit/anaconda/bin/ipython notebook --profile=ocean
  501 18056 18055   0 12:44AM ttys000    0:00.85 /Users/amit/anaconda/python.app/Contents/MacOS/python /Users/amit/anaconda/bin/ipython notebook --profile=ocean

Upvotes: 11

Related Questions