我想将
git grep
与从标准输入获取的输入一起使用。有一个选项 --no-index
但根据 documentation 它只允许 grep 当前目录中的文件:
--无索引
搜索当前目录中不受Git管理的文件。
我想使用
git grep
,因为它有一个选项--function-context
,而普通的grep没有它。有没有办法用git grep
做到这一点?
要使用 stdin 实现与
git grep --function-context
类似的功能,您需要采用解决方法,因为 git grep
本身不支持 stdin 的输入。git grep
和 --no-index
选项。这将模拟 git grep
在标准输入上的操作。
一个
git-grep-stdin.sh
脚本可以是:
#!/bin/bash
# Create a temporary file
temp_file=$(mktemp)
# Make sure the temporary file is deleted on exit
trap "rm -f $temp_file" EXIT
# Read from stdin and write to the temporary file
cat > "$temp_file"
# Use git grep with --no-index and --function-context on the temporary file
git grep --no-index --function-context "$@" "$temp_file"
搭配使用:
chmod 755 git-grep-stdin.sh
echo "your stdin content here" | ./git-grep-stdin.sh your_search_term
注意:Git 2.45(2024 年第 2 季度),第 14 批 在
--no-index
选项上更清晰:
参见commit 6e9ef29、commit 4a9357a(2024 年 3 月 25 日),作者:Dragan Simic (
dragan-simic
)。gitster
-- 合并于 commit e4193dc,2024 年 4 月 3 日)
:进一步描述grep docs
并稍微改进格式--no-index
签署人:Dragan Simic
改进
的描述,让用户更清楚这个选项实际上在幕后做什么,以及它的目的是什么。--no-index
描述与--no-index
和--cached
选项之间的依赖关系,不能一起使用。--untracked
更详细地说,
和--cached
都让 git-grep(1) 处于通常状态,在这种状态下,它将目录视为本地 git 存储库,这与--untracked
使 git-grep(1) 对待不同该目录不是 git 存储库。--no-index
换句话说,我们应该告诉用户我们的软件可以做什么,而不是告诉用户要做什么。
git grep
现在包含在其 手册页中:
--no-index
搜索当前目录下不受Git管理的文件, 或者忽略当前目录是由 Git 管理的。这 与运行常规
实用程序及其 指定了grep(1)
选项,但还有一些额外的好处,例如 使用 pathspec 模式来限制路径;请参阅“pathspec”条目 在链接git:gitglossary [7]中了解更多信息。-r
此选项不能与
或--cached
一起使用。 另请参阅下面“配置”中的--untracked
。grep.fallbackToNoIndex