Test if a systemd unit is active in a bash script
Asked Answered
I

2

22

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?

Indigestive answered 5/5, 2015 at 14:49 Comment(1)
Actually systemctl status does return a status - as I found when doing systemctl status openvpn@<>. Where the values are 0 for running, and 3 for stopped. However, this command is interactive :(. Hence the @lars suggested systemctl is-active is the way to go, and better att the -q as suggested by @palswimGoogly
B
45

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
Byway answered 5/5, 2015 at 15:4 Comment(2)
Thanks, that's exactly what i was looking for! it seems i missed it in the manual. ^^'Indigestive
You can also use the -q switch so that you don't have to redirect output: systemctl -q is-active sshdDickens
F
16

If you want to check in a shell script, you can do:

if (systemctl -q is-active some_application.service)
    then
    echo "Application is still running."
    exit 1
fi

To check if a application is not running just add a exclamation mark in the condition.

Fabrice answered 13/4, 2018 at 10:53 Comment(5)
This if statement always resolved to true because the strings "active" and "inactive" are both true.Diggs
The script works fine in my production machines. If an application is running the script exits, else it continues the script.Fabrice
looks like the script is checking the return code of systemctl not the string returned. So it works.Yetta
"This if statement always resolved to true because the strings "active" and "inactive" are both true." -> I tested and it worked for me.Khelat
For the pair with -q flag it's better to check explicitly for status code. e.g. ` systemctl -q is-active some_application.service\n if [ $? -eq 0 ]; then\n echo 'App running'\n exit 0\n fi ` p.s. sorry for the mess with code block, it's impossibru to use newline for comments.Article

© 2022 - 2024 — McMap. All rights reserved.