为什么如果[!$(grep的-q)如果不grep的-q不工作的时候? [英] Why does if [ !$(grep -q) ] not work when if grep -q does?
问题描述
我遇到了麻烦,如果grep的语句在正常工作。在以下code段中,如果检查总是出现真实的(即,未找到的字),并且程序打印没有发现,即使该字已在〜/。记忆体
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 "\nNOT FOUND\n"
fi
done
然而,当我测试的以下的code代替previous段:
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.
那么,什么是错code的第一段?
推荐答案
许多事情是不对的第一个片段。
A number of things are wrong with that first snippet.
您不想 [...]
如果你想测试返回code。丢弃这些。
You don't want [ ... ]
if you want to test the return code. Drop those.
[]
不是如果
语法的一部分(你可以从你的第二个片段见)。
[]
is not part of the if
syntax (as you can see from your second snippet).
[
是一个外壳内置和二进制您的系统上。它只是一个返回code退出。 如果...;然后
测试返回code ...
。
[
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]
和 [文字]
是PTED为 [-n字]
这将是真实的,只要字
非空。鉴于!
是从来没有非空,将永远是正确的。
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所示,添加!
否定你的第二个片断与它<$ C $之间的空间C>的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
.
这篇关于为什么如果[!$(grep的-q)如果不grep的-q不工作的时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!