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
Place both commands in a command-group and redirect the whole command-group to
grep
: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 serviceIf 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:
Explanation:
It’s fast, clean and most important works in regular VM, docker container, etc.