我编写了以下 sed 行,尝试仅查看昨天和今天之间包含“错误”一词的日志文件,如果存在,则返回简单的 Y / N。
我实际上并没有给我我需要的适当回报。有人可以帮我指出哪里出了问题吗?
today="$(date +%Y-%m-%d)"
yesterday="$(date -d '24 hour ago' +%Y-%m-%d)"
iserror="$(if [ sed -n "/"$yesterday"/,/"$today"/p" /mnt/data/systemlogs/logstash/logs/pipeline.log | grep "ERROR" ] = "" ; then
echo "No"
else
echo "Yes"
fi;
)"
答案1
你的语法在这里是错误的:
iserror="$(if [ sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep "ERROR" ] = "" ; then
echo "No"
else
echo "Yes"
fi;
)"
该构造的语法if [ ]
是if [ condition ]
.if [ command ] condition
因为= ""
位于 之外,所以您已经拥有了[ ]
。运行该代码应该会出现一些语法错误:
$ iserror="$(if [ sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep "ERROR" ] = "" ; then
echo "No"
else
echo "Yes"
fi;
)"
bash: [: missing `]'
grep: ]: No such file or directory
grep: =: No such file or directory
grep: : No such file or directory
您正在尝试的是这样的:
iserror="$(if [ $(sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep "ERROR") = "" ] ; then
echo "No"
else
echo "Yes"
fi;
)"
但这也不好,因为如果grep
不返回任何内容,您将丢失一个参数并得到不同的错误:
$ iserror="$(if [ $(sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep "bERROR") = "" ] ; then
echo "No"
else
echo "Yes"
fi;
)"
bash: [: =: unary operator expected
相反,您可以使用grep -c
它始终返回一个数字,如果没有匹配则返回 0,如果有则返回匹配的数量:
iserror="$(if [ $(sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep -c "ERROR") -eq 0 ] ; then
echo "No"
else
echo "Yes"
fi;
)"
或者,更简单的是, usegrep -q
不会产生任何输出,但如果找到某些内容则成功退出,如果没有找到则失败:
iserror="$(sed -n "/"$yesterday"/,/"$today"/p" pipeline.log |
grep -q "ERROR" &&
echo Yes ||
echo No)"
顺便说一句,您还可以更多地利用此处,仅当相关行中sed
存在匹配项时才打印它:ERROR
iserror="$(if [ $(sed -n '/2022-10-26/,/2022-10-27/{ /ERROR/p }' pipeline.log | wc -l) -gt 0 ]; then
echo Yes;
else
echo No;
fi) "