Check if service exists in bash (CentOS and Ubuntu)

Posted on Feb 20, 2022

Question

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?

Answer

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"

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

Hope to help.