-maxdepth 是精准控制 find 搜索深度的最常用可靠方式,如 -maxdepth 1 仅检查当前目录直接项而不进入子目录,且必须紧接路径参数后使用。

只查当前目录(不进子目录)
加 -maxdepth 1,且必须紧接在路径参数之后:
-
find . -maxdepth 1 -name "*.log"→ 列出当前目录下所有.log文件,不扫描子目录里的 -
find /var/log -maxdepth 1 -type f -size +1M→ 只检查/var/log目录一级内的普通文件,跳过/var/log/nginx/等子路径
注意:. 是第 0 层,它的直接子项算第 1 层;-maxdepth 1 不会跳过子目录名本身(比如 ./backup 会被列出),但绝不会进去查里面的内容。
限制最大搜索层数(比如最多查两层)
设成更大的数字,就能覆盖更深的结构:
-
find project -maxdepth 2 -name "config.json"→ 查project/及其直接子目录(如project/src/)里的config.json,但不进project/src/utils/ -
find ~ -maxdepth 3 -type d -name ".git"→ 在家目录下最多往下找三层,找所有名为.git的目录
深度从起始路径开始计数,-maxdepth 0 只匹配路径本身(例如 find . -maxdepth 0 只输出 .),基本不用。
配合 -mindepth 排除顶层,只查深层
如果想跳过当前目录,只查子目录及更深层,用 -mindepth:
-
find . -mindepth 2 -name "Makefile"→ 忽略./Makefile和./src/Makefile,只匹配像./src/lib/Makefile这样至少在第二级子目录里的文件 -
-mindepth 1等价于跳过当前目录本身,从它的子项开始搜(但默认行为其实已包含这点,通常无需显式加)
别踩坑:位置和替代方案
-maxdepth 和 -mindepth 必须紧跟在路径参数后面,不能放在 -name 或 -type 后面,否则多数 shell 会报错或失效。
- ✅ 正确:
find /tmp -maxdepth 1 -name "temp_*" - ❌ 错误:
find /tmp -name "temp_*" -maxdepth 1(选项顺序错,可能被忽略)
不用 find 时,ls *.txt 或 echo *.log 能快速列当前目录匹配项,但无法按大小、时间、权限等筛选;-prune 虽可实现类似效果,但逻辑绕、易出错,日常推荐直接用 -maxdepth。


















