LoginSignup
6
3

More than 3 years have passed since last update.

grep で自身の検索プロセスを除外したい時

Last updated at Posted at 2019-12-10

Overview

$ ps aux | grep zsh
qiita   10548   0.6  0.0  4268056    808 s000  S+   11:43AM   0:00.00 grep zsh
qiita   1294   0.4  0.0  4334752   2896 s000  S    10:04AM   0:00.22 -zsh

grep で grep 自身のプロセスは無視して表示させたい時ありますよね。
そんな時に使える方法を2つ紹介します :thumbsup:

grep -v を使う

多分よく知られている方法。

$ ps aux | grep zsh | grep -v 'grep zsh'
qiita   1294   0.0  0.0  4334752   2896 s000  S    10:04AM   0:00.23 -zsh

もう一回パイプして grep -v 'grep *' で自身のプロセスを除外できます。

[](brackets) を使う

grep -v でもいいんですが、もう一個パイプを挟んでいる関係で余計にプロセスをフォークしていることが気になったりしませんか?そんな時は [](brackets) を使いましょう。

$ ps aux | grep [z]sh
qiita   1294   0.3  0.0  4334752   2896 s000  S    10:04AM   0:00.24 -zsh

仕組みとしては z 1文字 + sh という条件で検索が実行されるが、grep に渡されている文字列は [z]sh なので z 1文字 + sh という条件には引っかからないので表示されませんよ、という話。
エレガントですね。

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3