Test if a systemd unit is active in a bash script

math picture math · May 5, 2015 · Viewed 21.2k times · Source

I'm writing a script to automatically install a bind server on a CentOs 7 distribution.

I'm stuck with systemctl status, because it does not produce an error code (it's right, since a status is not an error) I can use.

What I want is to check whether the service is started (active). What is the best and efficient way to do this?

Answer

larsks picture larsks · May 5, 2015

The best way to check if a service is active is with the systemctl is-active command:

# systemctl start sshd
# systemctl is-active sshd >/dev/null 2>&1 && echo YES || echo NO
YES
# systemctl stop sshd
# systemctl is-active sshd >/dev/null 2>&1 && echo YES || echo NO
NO