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

 梁言一聚 发布于 2023-01-07 18:29

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

什么是最好的解决方案?

2 个回答
  • Rustam Mamat因此得到了赞誉:

    如果列出所有服务,您可以查看结果以查看其中的内容.例如:

    # Restart apache2 service, if it exists.    
    if service --status-all | grep -Fq 'apache2'; then    
      sudo service apache2 restart    
    fi
    

    2023-01-07 18:32 回答
  • 要获得一项服务的状态而不“ ping”所有其他服务,可以使用以下命令:

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

    顺便说一下,这就是bash(自动)完成中使用的东西(请参见文件/ 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" | cut -f1 -d' ') == $n.service ]]; then
            return 0
        else
            return 1
        fi
    }
    if service_exists systemd-networkd; then
        ...
    fi
    

    希望对您有所帮助。

    2023-01-07 18:32 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有