2

How can we know if systemd has finished to boot the system ?

I don't want to execute on cron job if the system is actually on boot process because of missing network connectivity. My script launched by cron would have a test on top, and it exits if the booting process is not finished like

#!/bin/sh
$STATE=`HERE ADD THE MISSING PART`
if [ $STATE != "active" ]; then
  exit
fi
# Actions to do on next cron after booting

If it can also provide me the information about shutting down process, as the problem can be the same..;

I was doing this with SystemV with runlevel command, but Systemd do not change the runlevel at end of boot.

Thanks

4
  • Use a systemd unit instead of cron and use After=network-online.target and/or Wants=network-online.target to start it after the network. Aug 9, 2018 at 7:03
  • You can run scripts at shutdown with systemd in a similar way Aug 9, 2018 at 7:05
  • @Gerald_Schneider : I must run the command regulary by cron, but I don't want to execute them if the boot process is not finished...
    – Dom
    Aug 9, 2018 at 7:06
  • 1
    systemd supports timer units which would satisfy that requirement
    – bodgit
    Aug 9, 2018 at 11:35

1 Answer 1

6

You can check the target you need to be active in order for your script to run. For example, in order for the network to be accessible, you need to check the network-online.target (systemctl check will return 0 if the checked unit is active)

The target systemd tries to reach is its "default" target, which can be queried by systemctl get-default. If that target is online, the system has finished booting (so you can issue systemctl status $(systemctl get-default) to check whether the boot process has finished)

Edit: If you want to monitor only the current state of the system, and you aren't interested in targets (i.e. you want to run your command only when everything is up and running), it is better to use the systemctl is-system-running command. It will output running is everything is fine, or degraded if the system is up but some of the services have failed (which may or may not indicate an error). The other states would indicate that your script shouldn't run. As a side note, it's usually better to check return values instead of parsing the text output, but the manpage doesn't specify return values, only says that anything other than "running" results of a nonzero exit code, so it might be safer to parse the output text.

See the manpage of systemctl for the possible output values.

2
  • And do you know how to catch when the system is going to halt as the same way ?
    – Dom
    Aug 9, 2018 at 11:34
  • Yes, use the is-system-running subcommand. I've updated my answer to include this as well.
    – Lacek
    Aug 9, 2018 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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