skip to Main Content

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.

3

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search