Check if service exists in bash (CentOS and Ubuntu

2019-03-18 07:05发布

问题:

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

Thinking:

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

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?

回答1:

Rustam Mamat gets the credit for this:

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


回答2:

To build off of Joel B's answer, here it is as a function (with a bit of flexibility added in. Note the complete lack of parameter checking; this will break if you don't pass in 2 parameters):

#!/bin/sh

serviceCommand() {
  if sudo service --status-all | grep -Fq ${1}; then
    sudo service ${1} ${2}
  fi
}

serviceCommand apache2 status


回答3:

#!/bin/sh

service=mysql
status=$(/etc/init.d/mysql status)
print "$status"
#echo $status > /var/log/mysql_status_log


回答4:

The problem with service --status-all from above answers is that it seems to ping each service, which can be quite long.

What about:

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

This is what is used in bash completion (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 }' ) )

Hope to help.



回答5:

Try this, as ps command can be used in both Ubuntu&RHEL, this should be work in both platform.

#!/bin/bash
ps cax | grep mysqld > /dev/null
if [ $? -eq 0 ]; then
  echo "mysqld service exists"
else
  echo "mysqld service not exists"
fi