Difference between ps | grep safe and ps | grep safe\$

265 views Asked by At
# ps  | grep safe
14592 root      136m S    /tmp/data/safe/safe
16210 root      1664 S    grep safe

# ps  | grep safe\$
14592 root      258m S    /tmp/data/safe/safe

So what does \$ mean? Is it a regular expression?

1

There are 1 answers

0
fedorqui On BEST ANSWER

Yes, it is a regex. $ is a regex character that means "end of line". So by saying grep safe\$ you are grepping all those lines whose name ends with safe and avoiding grep itself to be part of the output.

The thing here is that if you run the ps command and grep its output, the grep itself will be listed:

$ ps -ef | grep bash
me       30683  9114  0 10:25 pts/5    00:00:00 bash
me       30722  8859  0 10:33 pts/3    00:00:00 grep bash

So by saying grep safe\$, or its equivalent grep "safe$", you are adding a regular expression in the match that will make the grep itself to not show.

$ ps -ef | grep "bash$"
me       30683  9114  0 10:25 pts/5    00:00:00 bash

As a funny situation, if you use the -F option in grep, it will match exact string, so the only output you will get is the grep itself:

$ ps -ef | grep -F "bash$"
me       30722  8859  0 10:33 pts/3    00:00:00 grep -F bash$

The typical trick to do this is grep -v grep, but you can find others in More elegant "ps aux | grep -v grep". I like the one that says ps -ef | grep "[b]ash".