In systemd (especially in Debian), it doesn't seems to work properly using the various answers from here. For some services like pure-ftpd
if it's in disabled mode, it will not show up in service list when you trigger this command:
systemctl --all --type service
and when you start again the pure-ftpd
with systemctl start pure-ftpd
the list will appear again. So listing the service using systemctl --all --type service
will not work for all services. Take a look at this for more information.
So, this is the best code so far (improvement from @jehon's answer) to check if a service is exist (even it has status inactive, dead or whatever status it is):
#!/bin/bash
is_service_exists() {
local x=$1
if systemctl status "${x}" 2> /dev/null | grep -Fq "Active:"; then
return 0
else
return 1
fi
}
if is_service_exists 'pure-ftpd'; then
echo "Service found!"
else
echo "Service not found!"
fi
Explanation:
If systemctl status
found a service, it must have a text 'Active:' we filter using grep and it would return 0. If there is no 'Active:' text it would return 1.
If systemctl status
does not find the 'Active:' text, it will print out a standard error. So, I put redirection 2> /dev/null
to redirect the standard error. For example, if you are looking for the non existence service, you would get this error message if you don't put that error redirection:
Unit pure-ftpdd.service could not be found.
We don't want to have the above standard error message if you are doing scripting
EDIT:
Another method is to list out unit files which able to detect disabled service as pointed by @Anthony Rutledge for Debian system:
systemctl list-unit-files --type service | grep -F "pure-ftpd"
But using this method will not always work especially for older system because some unit files might not be detected using this command as explained in here. Also, using this method is slower if you have large unit-files that need to be filtered (as commented by @ygoe about heavy load on a small computer).
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. – Faultychkconfig <service>
only returns true if the service is configured to run in the current runlevel (according to the man page I have here).chkconfig --list
seems to have the desired behaviour here though (at the cost of success and failure output) but may or may not be any better than just checking for the existence of (and executability of) the init script itself. – Jegar