トップディレクトリもfindの処理対象

findコマンドでファイルを検索すると、検索のトップディレクトリがfindの条件に合うとき、それも出力される。例えばカレントディレクトリの中でディレクトリだけ表示したくfind -type dを実行しても、カレントディレクトリが表示されてしまう。

$ ls -1
dir1
dir2
file1
file2

$ find -type d
.
./dir1
./dir2

-mindepth 1

このような場合にトップディレクトリを消すためには、-mindepth 1とするといい。

$ man find

...

    -mindepth levels
       Do not apply any tests or actions at levels less than levels (a non-negative integer).
       -mindepth 1  means  process  all files except the command line arguments.

...

-mindepth 1 means process all files except the command line arguments.とは、findの引数に渡すパス以外のファイルに対して処理する、という意味なので、find . -mindepth 1だと.(つまりカレントディレクトリであり、検索のトップディレクトリ)以外に対して処理される。

$ find -mindepth 1 -type d
./dir1
./dir2

もしdir1の中にさらにディレクトリがあるとすると、以下のようになる。

$ find -mindepth 1 -type d
./dir1
./dir1/subdir1
./dir2

-mindepthに指定する数だけトップディレクトリから処理しないようになるので、subdir1だけ表示したければ2を指定すればいい。

$ find -mindepth 2 -type d
./dir1/subdir1

-maxdepth 1

反対にsubdir1を表示したくなければ、-mindepthと同時に-maxdepth 1を指定して、トップディレクトリより下の階層を処理しないようにする。

$ find -mindepth 1 -maxdepth 1 -type d
./dir1
./dir2