Running Scripts at Startup – init.d vs cron @reboot Explained

croninit-scriptscriptingstartupsysvinit

I am currently trying to understand the difference between init.d and cron @reboot for running a script at startup/booting of the system.

The use of @reboot (this method was mentioned in this forum by hs.chandra) is some what simpler, by simply going into crontab -e and creating a @reboot /some_directory/to_your/script/your_script.txt and then your_script.txt shall be executed every time the system is rebooted. An in depth explanation of @reboot is here

Alternatively by embedding /etc/init.d/your_script.txt into the second line of your script ie:

#!/bin/bash
# /etc/init.d/your_script.txt

You can run chmod +x /etc/init.d/your_script.txt and that should also result for your_script.txt to run every time the system is booted.

Q1: What are the key differences between the two?
Q2: Which is more robust?
Q3: Is there a better one out of the two?
Q4: Is this the correct way of embedding a script to run during booting?

I will be incorporating a bash .sh file to run during startup.

Best Answer

init.d, also known as SysV script, is meant to start and stop services during system initialization and shutdown. (/etc/init.d/ scripts are also run on systemd enabled systems for compatibility).

  • The script is executed during the boot and shutdown (by default).
  • The script should be an init.d script, not just a script . It should support start and stop and more (see Debian policy)
  • The script can be executed during the system boot (you can define when).

crontab (and therefore @reboot).

  • cron will execute any regular command or script, nothing special here.
  • any user can add a @reboot script (not just root)
  • on a Debian system with systemd: cron's @reboot is executed during multi-user.target.
  • on a Debian system with SysV (not systemd), crontab(5) mention: Please note that startup, as far as @reboot is concerned, is the time when the cron(8) daemon startup. In particular, it may be before some system daemons, or other facilities, were startup. This is due to the boot order sequence of the machine.
  • it's easy to schedule the same script at boot and periodically.

/etc/rc.local is often considered to be ugly or deprecated (at least by redhat), still it had some nice features:

  • rc.local will execute any regular command or script, nothing special here.
  • on a Debian system with SysV (not systemd): rc.local was (almost) the last service to start.
  • but on a Debian system with systemd: rc.local is executed after network.target by default (not network-online.target !)

Regarding systemd's network.target and network-online.target, read Running Services After the Network is up.

Related Question