shell脚本中预期的条件二元运算符

时间:2014-08-04 12:32:23

标签: shell

我正在尝试一个简单的程序来比较存储在日志文件中的字符串值,并收到如下错误,

#!/bin/bash

check_val1="successful"
check_val2="completed"
log="/compile.log"

if [[ grep $check_val1 $log -ne $check_val1 || grep $check_val2 $log -ne $check_val2 ]];
then
        echo "No Error"
else
        echo "Error"
fi


Error:

./simple.sh: line 7: conditional binary operator expected
./simple.sh: line 7: syntax error near `$check_val1'
./simple.sh: line 7: `if [[ grep $check_val1 $log -ne $check_val1 || grep $check_val2 $log -ne $check_val2 ]];'

2 个答案:

答案 0 :(得分:17)

问题出现在if [[...]]表达式中,您使用2 grep个命令而不使用命令替换,即$(grep 'pattern' file)

然而不是:

if [[ grep $check_val1 $log -ne $check_val1 || grep $check_val2 $log -ne $check_val2 ]]; then

您可以使用grep -q

if grep -q -e "$check_val1" -e "$check_val2" "$log"; then

根据man grep

-q, --quiet, --silent
         Quiet mode: suppress normal output.  grep will only search a file until a match 
         has been found, making searches potentially less expensive.

答案 1 :(得分:6)

[[分析测试命令。测试不支持仅通过键入命令

来测试命令的退出状态