How to Auto-Run Scripts on Linux Boot: Crontab @reboot vs Systemd
This guide explains three methods to automatically execute scripts after a Linux system boots—using the traditional /etc/rc.local approach, the @reboot option in crontab, and creating a dedicated Systemd service—providing step‑by‑step commands and examples for each technique.
1. Introduction
When a machine loses power and needs to restart many services, setting up an auto‑start script is essential. A common but inelegant method is to add a command to /etc/rc.local like the example below:
$ cat /etc/rc.local
bash /root/script/restart.shThis works, but there are cleaner alternatives. The following sections describe two better approaches.
2. Using Crontab
Crontab supports the @reboot directive to run commands after the system boots. First, edit the crontab file:
$ crontab -eThen add the following line:
@reboot /root/script/restart.shAfter saving, the script will automatically execute on every reboot. Additional advanced usage includes delaying execution, for example:
# Run the script 5 minutes after boot
@reboot sleep 300 && /home/wwwjobs/clean-static-cache.sh3. Using Systemd
Create a Systemd service file named restart.service:
$ vim /lib/systemd/system/restart.service
[Unit]
Description=restart
After=default.target
[Service]
ExecStart=/root/script/restart.sh
[Install]
WantedBy=default.targetEnable and start the service with:
$ systemctl daemon-reload
$ systemctl enable restart.serviceOnce enabled, the associated script will run automatically at boot.
4. Reference Documents
https://www.google.com
https://tinyurl.com/6ryafefw
https://www.cyberciti.biz/faq/linux-execute-cron-job-after-system-reboot/
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
