Home > Software design >  Check whether the service is installed or not in Linux
Check whether the service is installed or not in Linux

Time:04-04

I am trying to get the service whether it is installed or not. The script is working fine with systemctl but fails where systemctl is not installed. As an alternative to that I am using service command to check but by doing so I am unable to run the grep command to grep specific service. This script needs to run on multiple linux machine (some with systemctl and some without it). Any help would be appreciated

test.sh

#!/bin/bash

serviceName=ngnix.service

if (systemctl --all --type service || service --status-all) && grep -q "$serviceName";then
    echo "$serviceName exists."
else
    echo "$serviceName does NOT exist."
fi

output without systemctl:

./test.sh: line 5: systemctl: command not found
 [ ? ]  hwclock.sh
 [ - ]  mariadb
 [ - ]  nginx
 [ - ]  nginx-debug
 [ - ]  procps
 [ - ]  redis-server
 [ - ]  rsync

output with systemctl:

ngnix.service does NOT exist.

CodePudding user response:

Place both commands in a command-group and redirect the whole command-group to grep:

if { systemctl --all --type service || service --status-all; } 2>/dev/null |
  grep -q "$serviceName"; then
  echo "$serviceName exists."
else
  echo "$serviceName does NOT exist."
fi

CodePudding user response:

systemctl is a control utility for managing systemd units. You can try checking nginx presence inside /usr/lib/systemd/ in case of systemd based init system. Don't forget the philosophy "Everything is a file." See man systemd.unit for more explanation. For ancient distros with init init system check directory /etc/init.d/ see man service

CodePudding user response:

If you don't want to check if the system has sysV or initd inside you can search just for the binary. If the binary exists, you can assume that the package and the services are installed. For instance:

#!/usr/bin/env bash

is_nginx_exists=$(which nginx)

if [[ $? == 0 ]]; then
        echo "YES"
else
        echo "NO"
fi

Explanation:

which nginx - will try to find the nginx binary from a system wide
binaries list;

$? - this command determinate if previous command executed successfully. In our case 0 means that the binary was found;

It's fast, clean and most important works in regular VM, docker container, etc.

  • Related