用 git grep 搜索已跟踪文件

无需扫描 .git 内部即可搜索工作区或历史版本。

macOS搜索Git命令行低风险
运行 git grep -n "模式",带行号搜索已跟踪文件。

01命令

命令
$ git grep -n "TODO" HEAD~5

02作用说明

git grep 只搜索已跟踪内容、遵循 .gitignore,并可直接指定任意提交或标签,便于比较某字符串在不同版本中的样子,比在大型检出上递归 grep 更快。

03风险

风险低风险
使用条件Git 2.20+ (install with Homebrew or Xcode Command Line Tools)
系统兼容性macOS with Git installed (Homebrew or Xcode Command Line Tools)
!注意: 指定 HEAD~5 等树对象时搜索该版本;不指定则搜索工作区。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • git-grep documentation
    Git · vendor-doc · 2026-09-20
    依据: Documents git grep, which searches tracked files at a given tree.

最后验证: 2026-10-13 · 分类: 开发者

06相关方案