[NTLUG:Discuss] keep grep command out of the results of a "ps | grep" *Solved but why?*

Wayne Walker wwalker at bybent.com
Thu Dec 11 16:08:30 CST 2008


I usually just do:

ps -elf | grep foo | grep -v grep

The reason that putting a backslash in the regex works is because what
is passed to grep is     a\getty   then grp converts \g to just g so
grep is looking for agetty which does not match the a\getty that is inn
the ps output for grep itself.

On Thu, Dec 11, 2008 at 04:02:18PM -0600, Richard wrote:
> Ok, so I want to see if a process is running.  Grepping the results of 
> ps sounds like a simple issue.  The problem is that executing grep with 
> the search terms will make the search always return true as it finds the 
> grep statement itself.
> 
> Now there is a solution to this problem that I already have, but I am at 
> a complete loss as to WHY it is working.
> 
> Let's say that we needed to see if the agetty process on tty2 was 
> running, executing the command:
> 
>  ps awx | grep agetty.*tty2 
> 
> ...will ensure that we only extract the lines on which appear: agetty, 
> plus any character, any number of times, followed by  tty2
> 
> This will leave us with TWO results  that might look something like this:
> 
>  3274 tty2     Ss+    0:00 /sbin/agetty 38400 tty2 linux
> 15482 pts/1    S+     0:00 grep agetty.*tty2
> 
> 
> Now take this second command that can be executed. 
> 
>  ps awx | grep a\\getty.*tty2
> 
> ..running the grep in that fashion causes ps to only return the agetty 
> process that is running and not the grep search process.
> 
>  3274 tty2     Ss+    0:00 /sbin/agetty 38400 tty2 linux
> 
> 
> Why is that?   the double backslash from the command line gets converted 
> and passed to grep as a single backslash which causes grep to escape the 
> g in agetty.  What is it about escaping the 'g' that causes grep to 
> exclude the process that is doing the grep(For instance, process 15482 
> in the example above)?  Why doesn't a\\getty match the agetty listed as 
> a parameter on the grep process line?
> 
> fwiw, running...
>  ps awx | grep 'a\getty.*tty2'
> ...works as well as the single backslash doesn't then have to be escaped.
> 
> -- 
> Richard
> 
> _______________________________________________
> http://www.ntlug.org/mailman/listinfo/discuss



More information about the Discuss mailing list