检查 bash 中是否存在服务(CentOS 和 Ubuntu) [英] Check if service exists in bash (CentOS and Ubuntu)

查看:17
本文介绍了检查 bash 中是否存在服务(CentOS 和 Ubuntu)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way in bash to check if a service is installed? It should work across both Red Hat (CentOS) and Ubuntu?

思考:

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

也可以使用service命令查看返回码.

Could also use the service command and check the return code.

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

什么是最好的解决方案?

What is the best solution?

推荐答案

在不ping"的情况下获取一个服务的状态所有其他服务,您可以使用命令:

To get the status of one service without "pinging" all other services, you can use the command:

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

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

By the way, this is what is used in bash (auto-)completion (see in file /usr/share/bash-completion/bash_completion, look for _services):

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

或者更复杂的解决方案:

Or a more elaborate solution:

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

希望能提供帮助.

这篇关于检查 bash 中是否存在服务(CentOS 和 Ubuntu)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆