【问题标题】:How to create shell script to check the status of systemd services in Ubuntu?如何创建 shell 脚本来检查 Ubuntu 中 systemd 服务的状态?
【发布时间】:2021-05-19 04:26:15
【问题描述】:

我有 5 个服务在 ubuntu 中运行。我每天检查他们的状态,所以必须为所有 5 项服务输入sudo systemctl status <> 命令。所以我想创建一个简单的脚本service_status.sh,它会列出状态。如下所示:

sudo systemctl status receiver0.service
sleep 2
sudo systemctl status receiver1.service
sleep 2
sudo systemctl status receiver2.service
sleep 2
sudo systemctl status sender.service
sleep 2
sudo systemctl status health.service

这运行良好并显示服务的状态,但问题是如果这些服务中的任何一个处于非活动状态或重新启动,那么脚本将冻结它们并且不显示剩余服务的状态。例如,如果 receiver2.service 由于某种原因没有运行:

● receiver2.service -  receiver 2
   Loaded: loaded (/etc/systemd/system/receiver2.service; enabled; vendor preset: enabled)
   Active: activating (auto-restart) (Result: exit-code) since Wed 2021-05-19 07:15:34 EAT; 25s ago
  Process: 5333 ExecStart=/usr/bin/python3 /home/andrew/Documents/source/receiver_
 Main PID: 5333 (code=exited, status=1/FAILURE)
lines 1-5/5 (END)

脚本在此停止并且不显示sender.servicehealth.service 的状态。我可以在脚本中进行哪些更改以使其不会冻结并同时显示其他服务的状态?

【问题讨论】:

  • 它可能会返回一个错误,而 bash 可能会返回该错误。您应该将返回值存储在一个变量中,然后您可以处理它、忽略它或执行these solutions 之一

标签: ubuntu service systemd


【解决方案1】:

使用is-active 并检查命令的返回码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 2016-12-29
    • 2013-01-05
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多