我想 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 $status
:status: Unknown job: =
您可以利用 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)
无论如何,请注意关键字inactive
、not active
或active (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)
归档时间: |
|
查看次数: |
24153 次 |
最近记录: |