Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if service exists in bash (CentOS and 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?

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?

like image 355
Justin Avatar asked Jun 25 '14 00:06

Justin


People also ask

How do I check if a service is running in bash?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

How do you check if a service is installed in Ubuntu?

User chkconfig <servicename> to check its presence. The return value is 0 if it is present and 1 if not. service <servicename> status returns the status of a service.


2 Answers

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.

like image 168
jehon Avatar answered Sep 16 '22 23:09

jehon


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 
like image 43
Joel B Avatar answered Sep 17 '22 23:09

Joel B