When using grep
in
Linux
to filter the output of ps
, you most likely end up having your grep process included in that list.
Even though the grep process itself is seldomly what you want.
Example:
$ ps -ef | grep postgres
postgres 1027 1 0 08:34 ? 00:00:00 /usr/lib/postgresql/11/bin/postgres -D /var/lib/postgresql/11/main -c config_file=/etc/postgresql/11/main/postgresql.conf
postgres 1075 1027 0 08:34 ? 00:00:00 postgres: 11/main: checkpointer
postgres 1076 1027 0 08:34 ? 00:00:00 postgres: 11/main: background writer
postgres 1077 1027 0 08:34 ? 00:00:00 postgres: 11/main: walwriter
postgres 1078 1027 0 08:34 ? 00:00:00 postgres: 11/main: autovacuum launcher
postgres 1079 1027 0 08:34 ? 00:00:00 postgres: 11/main: stats collector
postgres 1080 1027 0 08:34 ? 00:00:00 postgres: 11/main: logical replication launcher
user 12865 12636 0 15:22 pts/4 00:00:00 grep --color=auto postgres
This happens because the grep process includes the grep command line which obviously includes the pattern that grep uses to filter the process list.
A neat trick to avoid having grep include itself in the process list is to put square brackets around the first letter of the pattern. Example:
$ ps -ef |grep [p]ostgres
postgres 1027 1 0 08:34 ? 00:00:00 /usr/lib/postgresql/11/bin/postgres -D /var/lib/postgresql/11/main -c config_file=/etc/postgresql/11/main/postgresql.conf
postgres 1075 1027 0 08:34 ? 00:00:00 postgres: 11/main: checkpointer
postgres 1076 1027 0 08:34 ? 00:00:00 postgres: 11/main: background writer
postgres 1077 1027 0 08:34 ? 00:00:00 postgres: 11/main: walwriter
postgres 1078 1027 0 08:34 ? 00:00:00 postgres: 11/main: autovacuum launcher
postgres 1079 1027 0 08:34 ? 00:00:00 postgres: 11/main: stats collector
postgres 1080 1027 0 08:34 ? 00:00:00 postgres: 11/main: logical replication launcher
Why does this work?
Well, [p]ostgres
instructs grep to match any line that contains the letter inside the brackets p
followed by the string ostgres
.
And that’s the magic: now the grep command does not include postgres
but it does match postgres
.