Grep trick: The square brackets in the grepped ps output

I ofter use square brackets in the grepped ps output like:

  • ps -ef | grep [b]ash instead of ps -ef | grep bash.

The square brackets are used for eliminating the grep itself in the ps output.

Explanation:

If you run ps -ef | grep string, the grep is displayed because it matches the “string”, in the grep.

When you run ps -ef | grep [s]tring the grep translates [s]tring to string and does not display the grep line.

$ ps -ef | grep ssh
root 445 1 0 09:23 ? 00:00:00 /usr/sbin/sshd -D
115 2317 2267 0 09:33 ? 00:00:00 /usr/bin/ssh-agent /usr/bin/dbus-launch --exit-with-session gnome-session --session=gnome
root 7306 445 0 15:50 ? 00:00:00 sshd: razvan [priv]
razvan 7411 7306 0 15:51 ? 00:00:00 sshd: razvan@pts/1
root 8412 445 0 17:29 ? 00:00:00 sshd: razvan [priv]
razvan 8517 8412 0 17:29 ? 00:00:01 sshd: razvan@pts/2
razvan 11003 8518 0 18:19 pts/2 00:00:00 grep --colour=auto ssh

$ ps -ef | grep [s]sh
root 445 1 0 09:23 ? 00:00:00 /usr/sbin/sshd -D
115 2317 2267 0 09:33 ? 00:00:00 /usr/bin/ssh-agent /usr/bin/dbus-launch --exit-with-session gnome-session --session=gnome
root 7306 445 0 15:50 ? 00:00:00 sshd: razvan [priv]
razvan 7411 7306 0 15:51 ? 00:00:00 sshd: razvan@pts/1
root 8412 445 0 17:29 ? 00:00:00 sshd: razvan [priv]
razvan 8517 8412 0 17:29 ? 00:00:01 sshd: razvan@pts/2

$ ps -ef | grep bash
115 2524 2507 0 09:34 pts/0 00:00:00 bash
razvan 2584 2576 0 09:34 pts/0 00:00:02 bash
razvan 7412 7411 0 15:51 pts/1 00:00:01 -bash
razvan 8518 8517 0 17:29 pts/2 00:00:01 -bash
razvan 11039 8518 0 18:27 pts/2 00:00:00 grep --colour=auto bash

$ ps -ef | grep [b]ash
115 2524 2507 0 09:34 pts/0 00:00:00 bash
razvan 2584 2576 0 09:34 pts/0 00:00:02 bash
razvan 7412 7411 0 15:51 pts/1 00:00:01 -bash
razvan 8518 8517 0 17:29 pts/2 00:00:02 -bash

Tagged with: , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Subscribe

  

Subscribe to get the latest Linux news and how to guides directly on your e-mail!