为什么 if [ !$(grep -q) ] 在 if grep -q 起作用时不起作用? [英] Why does if [ !$(grep -q) ] not work when if grep -q does?
问题描述
我无法让 grep 在 if 语句中正常工作.在下面的代码段中,if-check 总是为真(即找不到单词),即使单词已经在 ~/.memory 中,程序也会打印 NOT FOUND.
I'm having trouble getting grep to work properly in an if statement. In the following code segment, the if-check always comes up true (i.e. the word is not found), and the program prints NOT FOUND, even though the words are already in ~/.memory.
for (( i=0; i<${#aspellwords[*]}; i++)); do
if [ !$(grep -q "${aspellwords[$i]}" ~/.memory) ]; then
words[$i]="${aspellwords[$i]}"
printf "
NOT FOUND
"
fi
done
但是,当我测试以下代码代替前一段时:
However, when I test the following code in place of the previous segment:
for (( i=0; i<${#aspellwords[*]}; i++)); do
if grep -q "${aspellwords[$i]}" ~/.memory; then echo FOUND IT; fi
done
它工作得非常好,可以毫无问题地找到这个词.
It works perfectly fine and finds the word without any issues.
那么第一段代码有什么问题?
推荐答案
第一个片段有很多问题.
A number of things are wrong with that first snippet.
如果你想测试返回码,你不需要 [ ... ]
.放下那些.
You don't want [ ... ]
if you want to test the return code. Drop those.
[]
不是 if
语法的一部分(正如您在第二个代码段中所见).
[]
is not part of the if
syntax (as you can see from your second snippet).
[
是您系统上的内置 shell 和二进制文件.它只是以返回码退出.<代码>如果...;然后测试...
的返回码.
[
is a shell built-in and binary on your system. It just exits with a return code. if ...; then
tests the return code of ...
.
$()
是命令替换.它用所运行命令的输出替换自己.
$()
is command substitution. It replaces itself with the output from the command that was run.
所以 [ !$(grep ...) ]
实际上是在评估 [ !output_from_grep ]
并且 [ word ]
被解释为 [ -n word ]
只要 word
不为空,它就会为真.鉴于 !
永远不会是非空的,这将永远是真的.
So [ !$(grep ...) ]
is actually evaluating [ !output_from_grep ]
and [ word ]
is interpreted as [ -n word ]
which will be true whenever word
is non-empty. Given that !
is never non-empty that will always be true.
简单地,正如@thom 在他的评论中所指出的(有点倾斜),将 !
否定添加到您的第二个片段中,并在它和 grep
之间添加一个空格.
Simply, as indicated by @thom in his comment (a bit obliquely), add the !
negation to your second snippet with a space between it and grep
.
这篇关于为什么 if [ !$(grep -q) ] 在 if grep -q 起作用时不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!