检查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

什么是最佳解决方案?

Rustam Mamat为此赢得了荣誉:

Rustam Mamat gets the credit for this:

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

If you list all your services, you can grep the results to see what's in there. E.g.:

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