4

I have a script that I want to run during my next system boot, but not on subsequent boots. I want to use systemd to launch it, so I created a service file at /usr/lib/systemd/system/myscript.service:

[Unit]
Description=My script.

[Service]
Type=oneshot
ExecStart=/opt/mypackage/bin/myscript

[Install]
WantedBy=multi-user.target

I can tell systemd to run this service at boot using systemctl enable myscript.service.

What do I need to do in order to stop it from running on subsequent boots?

I can add systemctl disable myscript.service to the end of my script, but then that always disables the service. If possible I would like to be able to enable the service, then start it, and still have it execute on next boot.

5

You may use the ConditionPathExists= directive (see systemd.unit(5)) to conditionally start a unit. This allows you to leave the unit permanently enabled and to (temporarily) disable it by deleting a simple file.

There is no distinction between "started at boot" and "started from systemctl start" in systemd. A workaround would be to check the uptime in your script in order to take the decision to enable/disable the unit on next boot (by deleting/creating the ConditionPathExists= file).

5

Note: this answer extends Siosm's answer, and includes an alternative solution. If you agree with the first part, please upvote Siosm's answer instead.

In vein with Siosm's answer, use ConditionPathExists= and ConditionPathNotExists in section [Path] of the unit's service file (see systemd.path(5)) in order to make the running of your service conditional.

For instance, if myscript's responsibility is to create a file or a folder once, add startup conditions that reflect this: ConditionPathNotExists=/path/to/folder.

Conversely, you can have the ConditionPathExists point to a file such as /var/tmp/myscript.on-next-reboot that the script is tasked to remove after running successfully. You can probably add the removal as the unit's ExecStartPost= directive.


In general, though, you should try to work your system so that after-reboot actions are not necessary. Setting things to run at next boot is very "Windows-like" in attitude. Linux users and administrators tend to favor deterministic, modular and previsible boots; having conditional run-time values trigger different paths of boot makes boot system much harder to reason about, and it makes it more prone to breakage.

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.