6

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.

2 Answers 2

7

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).

6

Note: this answer extends the answer by Timothée Ravier (Timothée previously used the name Siosm on this site), and includes an alternative solution.  If you agree with the first part, please up vote Timothée’s answer instead.

In vein with Timothée Ravier’s answer, use ConditionPathExists= in section [Unit] of the unit’s service file (see systemd.unit(5) at freedesktop.org or at man7.org) 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: ConditionPathExists=!/path/to/folder.  Note the !, which negates (inverts) the sense of the condition; the service unit is started only if the path does not exist.

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.

You must log in to answer this question.

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