Why does the exit status differ when running `systemctl start; systemctl is-active` and `systemctl is-active` separately?
When I encounter an issue like this, I tend to follow Sherlock Holmes’ mantra, and consider what is left, however implausible, once the impossible is eliminated. Of course with computers nothing is impossible, however some things are so unlikely we can ignore them at first. (This makes more sense with the original title, “command; command; echo $?
— return value is not correct, why?”)
In this case, if
sudo systemctl start x; sudo systemctl is-active --quiet x; echo $?;
shows that $?
is 0, that means that systemctl is-active
really did indicate success. The fact that a separate systemctl is-active
shows that the service isn’t active strongly suggests that there’s a race between the service and the human operator typing the commands; basically, that the service does start, to a sufficient extent for systemctl start
to finish, and systemctl is-active
to run and find the service active, but then the service fails, so a human-entered systemctl is-active
finds it inactive.
Adding a short delay between systemctl start
and systemctl is-active
should avoid the false positive.
Systemd brings the service up for a short time (0.1
seconds) and then the service crashes.
Returns 3
as it should be;
sudo systemctl start x; sleep 0.2; sudo systemctl is-active --quiet x; echo $?;
Less, than 0.2
seconds, it returns 0
as it should not be:
sudo systemctl start x; sleep 0.1; sudo systemctl is-active --quiet x; echo $?;
Also if I do systemctl start x; ps -fA | grep -i x
I see the service. If I run ps
again after that, it's gone.