在外壳一线使用grep -q [英] Using grep -q in shell one-liners
问题描述
我编写了一个脚本来列出包含特定文件的回购中的提交.它运行良好,但是我不明白为什么要这样写:
I've written a script to list commits in a repo that contain a specific file. It's working perfectly, but I don't understand why I had to write this:
for c in $(git rev-list "$rev_list"); do
git ls-tree --name-only -r "$c" | grep -q "$file"
if [ $? -eq 0 ]; then
echo "Saw $file in $c"
fi
done
我通常这样写:
[[ $(git ls-tree --name-only -r "$c" | grep -q "$file") ]] && echo "Saw $file in $c"
# or
[[ ! $(git ls-tree --name-only -r "$c" | grep -q "$file") ]] || echo "Saw $file in $c"
这两个简短版本都不起作用:它们不输出任何内容.当我编写它以使其显示不包含该文件的所有提交时,我确实得到了输出:
Neither of the short versions work: they don't output anything. When I write it so that it shows all commits that don't contain the file, I do get output:
[[ $(git ls-tree --name-only -r "$c" | grep -q "$file") ]] || echo "Did not see $file in $c"
但是,如果我然后从输出中获取提交哈希并运行
However, if I then take a commit hash from the output and run
git ls-tree -r <the hash> | grep file
我注意到树中的某些提交文件 ,使我相信它只是列出了脚本处理的所有提交.无论哪种方式,我都可能会丢失一些东西,但是我无法确切知道它是什么
I notice the file is in the tree for some commits, leading me to believe it's just listing all the commits the script processes. Either way, I'm probably missing something, but I can't exactly work out what it is
推荐答案
您无需将命令包装在条件语句([[ $(command) ]]
)中.实际上,这对grep -q
永远无效,因为您实际上正在测试命令是否可以打印.您可以这样做:
You don't need to wrap the command in a conditional statement ([[ $(command) ]]
). In fact, that will never work with grep -q
, because you're actually testing whether the command prints anything. You can just do this:
git ls-tree --name-only -r "$c" | grep -q "$file" && echo "Saw $file in $c"
一般来说,任何类似的代码块
In general, any code block like
foreground_command
if [ $? -eq 0 ]
then
bar
fi
可以替换为
if foreground_command
then
bar
fi
甚至
foreground_command && bar
您应该使用的三种选择中的哪种取决于foreground_command
,bar
还是两者都是多行命令.
Which of the three alternatives you should use depends on whether foreground_command
, bar
, or both are multi-line commands.
这篇关于在外壳一线使用grep -q的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!