I'm trying to write code which programmatically check service status, but is also robust to typos in service names. In my opinion a reasonable program to use would have the following behavior and semantics:

  • it takes a unit name as an argument
  • if that unit is found, it prints out the service status and exits with status 0 (eg active,inactive,etc...)
  • if that unit is not found/loaded, it prints out an error and exits with a non-zero status

Notably these do not meet this requirement:

  • systemctl is-active servicename (exits with non-zero return status if the unit is not active, identical behavior if servicename is not loaded)
  • systemctl is-failed servicename (similar behavior to above)
  • systemctl show servicename -pActiveState (exits with status 0 if servicename is not loaded)

It seems like the closest thing is systemctl show servicename -pLoadState -pActiveState but then I have to parse the LoadState string to determine if there's a typo, which seems more complex than should be required for this simple task.

Any suggestions?

closed as primarily opinion-based by Rui F Ribeiro, Mr Shunz, Kiwy, Alexander, telcoM Apr 28 at 23:01

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • perhaps your script could check for the existence of the service before asking for the status? – Jeff Schaller Apr 24 at 15:12
  • the semantics just set us up for failure. If there's a typo somewhere, or a service name changes and someone forgets to change the name in a particular place everything will operate "normally" and just subtly be broken. – jdizzle Apr 25 at 16:35

Any suggestions?

Encourage the systemd people to fix the bug that is still open from 2014.

The systemctl manual documents an appropriate LSB version 3 exit status, known within systemd as EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN, and this exit status is even used by systemctl status for nonexistent services, distinguishing them from services that exist but that are not running.

It is not, however, used by systemctl is-active.

Further reading

Not the answer you're looking for? Browse other questions tagged or ask your own question.