21

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?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
math
  • 311
  • 1
  • 2
  • 3
  • 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 @palswim – SACHIN GARG Jul 14 '16 at 18:51

2 Answers2

43

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
larsks
  • 277,717
  • 41
  • 399
  • 399
  • Thanks, that's exactly what i was looking for! it seems i missed it in the manual. ^^' – math May 06 '15 at 07:28
  • 15
    You can also use the `-q` switch so that you don't have to redirect output: `systemctl -q is-active sshd` – palswim Apr 05 '16 at 18:37
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.

voliveira89
  • 1,134
  • 2
  • 9
  • 22
  • This if statement always resolved to true because the strings "active" and "inactive" are both true. – J-a-n-u-s Jun 13 '18 at 22:28
  • The script works fine in my production machines. If an application is running the script exits, else it continues the script. – voliveira89 Jun 15 '18 at 10:08
  • 2
    looks like the script is checking the return code of systemctl not the string returned. So it works. – Michael West Jun 15 '18 at 17:51
  • 1
    "This if statement always resolved to true because the strings "active" and "inactive" are both true." -> I tested and it worked for me. – Eduardo Lucio Aug 28 '18 at 16:05
  • 1
    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. – sfate Sep 15 '18 at 14:27