Check if service exists in bash (CentOS and Ubuntu)
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.
On a SystemD system :
serviceName="Name of your service"if systemctl --all --type service | grep -q "$serviceName";then echo "$serviceName exists."else echo "$serviceName does NOT exist."fi
On a Upstart system :
serviceName="Name of your service"if initctl list | grep -q "$serviceName";then echo "$serviceName exists."else echo "$serviceName does NOT exist."fi
On a SysV (System V) system :
serviceName="Name of your service"if service --status-all | grep -q "$serviceName";then echo "$serviceName exists."else echo "$serviceName does NOT exist."fi