LoginSignup
0
0

More than 1 year has passed since last update.

findコマンドのエラーメッセージをgrep -vで除外したいのに出来なかった時の話

Posted at

結論、標準出力(stdout)と標準エラー出力(stderr)は違うからね!

あるファイルを探したくて、次のようなコマンドラインを打ったところ、Operation not permittedがたくさん!

/bin/zsh
$ find . -iname filename     <- -inameは大文字小文字区別しないオプション
find: ./Library/Application Support/MobileSync: Operation not permitted
find: ./Library/Application Support/CallHistoryTransactions: Operation not permitted
find: ./Library/Application Support/CloudDocs/session/db: Operation not permitted
find: ./Library/Application Support/com.apple.sharedfilelist: Operation not permitted
find: ./Library/Application Support/Knowledge: Operation not permitted
find: ./Library/Application Support/com.apple.TCC: Operation not permitted
...
./Downloads/filename.    <- 目的のファイル!

Operation not permittedがダダーっと!見づらい。。。
そうだ、grep -v で除外すればいいんだ!(-v は後に続く文字列を除外するオプション)
(いや、待て、もっとシンプルな方法があるだろ。。。(後で気づく))

/bin/zsh
$ find . -iname filename | grep -v "not permitted"
find: ./Library/Application Support/MobileSync: Operation not permitted
find: ./Library/Application Support/CallHistoryTransactions: Operation not permitted
find: ./Library/Application Support/CloudDocs/session/db: Operation not permitted
find: ./Library/Application Support/com.apple.sharedfilelist: Operation not permitted
find: ./Library/Application Support/Knowledge: Operation not permitted
find: ./Library/Application Support/com.apple.TCC: Operation not permitted
...
./Downloads/filename.    <- 目的のファイル!

あれ? Operation not permittedを含む行が除外されない!なんで???

ググるとやっぱり同じような思いの人が見つかります。
How can I exclude all "permission denied" messages from "find"?

上記stack overflowのスレッド参考にすると、以下のようにすれば良いとのこと。
find . -iname filename 2>&1 | grep -v "not permitted"

2は標準エラー出力(stderr)。
1は標準出力(stdout)。※ &はリダイレクトの文脈(>のあと)においてファイル名ではなくファイルディスクリプタであること意味する。
つまり標準エラー出力を標準出力にリダイレクトしてるんですね。
パイプが渡すのは標準出力の方だけということが分かりました。

あーこれで解決!

...

ってもっとシンプルな方法あるやんけ。
find . -iname filename 2>/dev/null

でもエラーメッセージ全部除外するんじゃなくて一部のみ除外って時はstderrをstdoutへリダイレクトするのが役立つね!ってことで勉強になりました。

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