Bourne shell 多个 if 条件与 grep

Bourne shell multiple if conditions with grep

使用 Bourne shell 4.2,我试图在 if 语句中使用两个条件,其中之一是 grep:

file=/tmp/file
cat $file
this is an error i am looking for
if [ -e "$file" ] && [ $(grep -q 'error' $file) ]; then echo "true"; else echo "false"; fi
false

我希望此处返回“true”,因为两个条件都为真。

但是,这有效:

grep_count=$(grep --count 'error' /tmp/file)
if [ -e "$file" ] && [ $grep_count -gt 0 ]; then echo "true"; else echo "false"; fi
true

最后:

test -e /tmp/file
echo $?
0
grep -q 'error' /tmp/file
echo $?
0

我错过了什么?如何在 if 语句中使用 grep?

您误用了测试括号内的命令替换:

if [ -e "$file" ] && [ $(grep -q 'error' $file) ]; then echo "true"; else echo "false"; fi

应该写成:

if [ -e "$file" ] && ( grep -q 'error' $file ); then echo "true"; else echo "false"; fi

命令替换 $(command) 允许用命令的输出替换命令名称本身。因此,您所做的是测试空字符串的内容,例如:

[ "" ]

其中return'1',让你的条件不满足。