检查 bash 中是否存在服务(CentOS 和 Ubuntu)

新手上路,请多包涵

bash 中检查服务是否已安装的最佳方法是什么?它应该适用于 Red Hat (CentOS) 和 Ubuntu?

思维:

 service="mysqld"
if [ -f "/etc/init.d/$service" ]; then
    # mysqld service exists
fi

也可以使用 service 命令并检查返回码。

 service mysqld status
if [ $? = 0 ]; then
    # mysqld service exists
fi

什么是最好的解决方案?

原文由 Justin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 779
1 个回答

要在不“ping”所有其他服务的情况下获取一项服务的状态,可以使用以下命令:

 systemctl list-units --full -all | grep -Fq "$SERVICENAME.service"

顺便说一句,这就是 bash (auto-)completion 中使用的内容(参见文件 /usr/share/bash-completion/bash_completion,查找 _services):

 COMPREPLY+=( $( systemctl list-units --full --all 2>/dev/null | \
   awk '$1 ~ /\.service$/ { sub("\\.service$", "", $1); print $1 }' ) )

或者更详细的解决方案:

 service_exists() {
    local n=$1
    if [[ $(systemctl list-units --all -t service --full --no-legend "$n.service" | sed 's/^\s*//g' | cut -f1 -d' ') == $n.service ]]; then
        return 0
    else
        return 1
    fi
}
if service_exists systemd-networkd; then
    ...
fi

希望有所帮助。

原文由 jehon 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题