Auto-Run Scripts on Linux Boot: rc.local, crontab @reboot, and systemd Service
This guide shows three practical ways to execute custom scripts automatically after a Linux system starts—by editing /etc/rc.d/rc.local, configuring a crontab @reboot entry, or creating a systemd service—complete with commands, sample scripts, and troubleshooting tips.
Method 1: Edit /etc/rc.d/rc.local
The /etc/rc.d/rc.local file runs after all system services have started, making it a convenient place to launch custom scripts. Ensure the file is executable, then add the script path at the end of the file. chmod +x /etc/rc.d/rc.local Create a simple script that writes the date and hostname to a file in the home directory:
vim auto_run_script.sh
#!/bin/bash
date >> /home/alvin/output.txt
hostname >> /home/alvin/output.txtMake the script executable: chmod +x auto_run_script.sh Append the script call to /etc/rc.d/rc.local (the last line before exit 0 if present):
vim /etc/rc.d/rc.local
/home/alvin/auto_run_script.shReboot the system ( sudo reboot) and verify that output.txt contains the expected data.
Method 2: Use crontab with @reboot
The crontab utility can schedule tasks; the special @reboot keyword runs a command each time the system boots.
crontab -e
@reboot /home/alvin/auto_run_script.shSave the file and reboot; the script will execute automatically, producing the same result as Method 1.
Method 3: Create a systemd Service
First confirm the host uses systemd by checking the PID 1 process: ps aux | grep "1 .*systemd" Create a service unit file named auto_run_script.service:
vim /etc/systemd/system/auto_run_script.service
[Unit]
Description=Run a Custom Script at Startup
After=default.target
[Service]
ExecStart=/home/alvin/auto_run_script.sh
[Install]
WantedBy=default.targetReload the systemd manager configuration and enable the service to start at boot:
systemctl daemon-reload
systemctl enable auto_run_script.serviceFinally, reboot the machine ( reboot) and verify that the script runs as expected.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
