shell脚本中需要条件二进制运算符

cs7cruho  于 2023-04-07  发布在  Shell
关注(0)|答案(2)|浏览(189)

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

#!/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 ]];'
tct7dpnv

tct7dpnv1#

[[触发test命令。Test不支持仅通过键入命令来测试命令的退出状态

pu82cl6c

pu82cl6c2#

问题出在你的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.

相关问题