测试 systemd 单元是否在 bash 脚本中处于活动状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30056280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if a systemd unit is active in a bash script
提问by math
I'm writing a script to automatically install a bind server on a CentOs 7 distribution.
我正在编写一个脚本来在 CentOs 7 发行版上自动安装绑定服务器。
I'm stuck with systemctl status
, because it does not produce an error code (it's right, since a status is not an error) I can use.
我坚持使用systemctl status
,因为它不会产生我可以使用的错误代码(这是正确的,因为状态不是错误)。
What I want is to check whether the service is started (active). What is the best and efficient way to do this?
我想要的是检查服务是否已启动(活动)。做到这一点的最佳和有效方法是什么?
回答by larsks
The best way to check if a service is active is with the systemctl is-active
command:
检查服务是否处于活动状态的最佳方法是使用以下systemctl is-active
命令:
# systemctl start sshd
# systemctl is-active sshd >/dev/null 2>&1 && echo YES || echo NO
YES
# systemctl stop sshd
# systemctl is-active sshd >/dev/null 2>&1 && echo YES || echo NO
NO
回答by voliveira89
If you want to check in a shell script, you can do:
如果要签入 shell 脚本,可以执行以下操作:
if (systemctl -q is-active some_application.service)
then
echo "Application is still running."
exit 1
fi
To check if a application is not running just add a exclamation mark in the condition.
要检查应用程序是否未运行,只需在条件中添加感叹号即可。