1

If I run a systemctl command for a non-existant service (foo.service) (e.g. systemctl stop foo.service), systemd fails (exit code 5, & stderr: Failed to stop foo.service: Unit foo.service not loaded.).

Is it possible to detect, in my bash script, if a service (or .timer) would fail like that before running the systemctl command? systemd has systemctl is-active NAME.service. There is no systemctl is-loaded. What's the Best™ way to detect this? systemctl list-units? systemctl status?

I am writing a script which restarts (well try-restarts) a .timer or .service. If the timer doesn't exist, I don't want an error to happen. If it does exist, and the try-restart fails, I want to detect, and raise, that error.

systemd v245 etc on latest Ubuntu LTSs (e.g. 20.04)

1 Answer 1

3

systemctl status will exit with a return code indicating the status of the service. From the man page:

Value Description in LSB                               Use in systemd

0     "program is running or service is OK"            unit is active 
1     "program is dead and /var/run pid file exists"   unit not failed (used by is-failed) 
2     "program is dead and /var/lock lock file exists" unused 
3     "program is not running"                         unit is not active 
4     "program or service status is unknown"           no such unit 

A return code of 4 indicates an unknown service (one that would result in an error if you were to try and restart it).

But from your question, it looks like you could skip the check and just use the return code from systemctl restart (if rc=5, ignore the error, otherwise display the error and handle the failure, etc).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .