A cool trick that saves you from having to use grep -v when grepping ps output (yes I know pgrep exists) is to put the first letter of the process into a character class like ps -ef |grep [s]vn. This will exclude the grep svn from being included in the output. Why does this work? GNU grep.
2 Answers
Grep is searching for a regular expression, so for example [Pp]rocess will find Process or process, but an interesting side effect is that the command line of the grep operation has a ] stuck in there, which means that the grep line doesn't contain the word process, it contains the word p]rocess, which doesn't match.
So effectively you're removing the word process from your grep line by putting the closing bracket in there, but still allowing it to match the word on other lines.
- 15,155
Square brackets are part of grep's pattern matching. Basically grep gets basic regex:
[12p]rocess will expand to: 1rocess 2rocess process
Now, grep will actually search for [1]rocess [2]rocess [p]rocess which - as you can see - it's not process.
Square brackets are character class matching in regular expressions. You can read more about regualar expressions and character matching here:
- 653
http://serverfault.com/questions/367921/how-to-prevent-ps-reporting-its-own-process/367936
– jamzed May 22 '13 at 20:08