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

David Stanaway david at stanaway.net
Thu Dec 11 21:17:10 CST 2008


For that, I put [] about one of the characters in the search pattern.

eg: ps aux | grep [s]sh

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.
>
>   




More information about the Discuss mailing list