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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With