如何在 bash 中评估 grep 结果?

mem*_*und 5 bash grep

我想 grep 服务的特定状态 ( tomcat8.service)。

仅当找到该字符串时,我才想执行一些逻辑。

问题:即使我在不​​存在的服务名称(本例中为“asd”)上执行脚本,if $status仍然匹配并打印出来。但为什么?

status = $(systemctl status asd.service | grep 'active')
echo $status

if $status
then 
    echo "$SERVICE was active"
    exit 0
fi 
exit 0
Run Code Online (Sandbox Code Playgroud)

结果输出是:asd.service was active,这当然不是真的。

印刷品echo $statusstatus: Unknown job: =

pLu*_*umo 4

您可以利用 grep 的返回状态。

systemctl status asd.service | grep 'active' \
    && status=active \
    || status=not_active

if [ "$status" == "active" ]; then
    [...]
fi
Run Code Online (Sandbox Code Playgroud)

甚至更简单:

test $(systemctl status asd.service | grep 'active') \
    && echo "$SERVICE was active"
Run Code Online (Sandbox Code Playgroud)

或者如果您愿意if

if $(systemctl status asd.service | grep 'active'); then
    echo "$SERVICE was active"
fi
Run Code Online (Sandbox Code Playgroud)

无论如何,请注意关键字inactivenot activeactive (exited)类似的关键字。这也将符合您的grep陈述。看看评论。感谢@Terrance 的提示。


更新:

不需要 grep。systemctl包含该命令is-active

systemctl -q is-active asd.service \
    && echo "$SERVICE was active"
Run Code Online (Sandbox Code Playgroud)

或者:

if systemctl -q is-active asd.service; then
    echo "is active";
fi
Run Code Online (Sandbox Code Playgroud)