System administrators frequently need specific background tasks—such as starting a custom web server, mounting a non-standard network drive, or initiating a logging script—to launch automatically whenever a Linux machine powers on. While creating a full systemd service file is the modern standard for complex daemon management, it can be overly complicated for a simple bash script. The fastest and easiest way to run a script on startup is by utilizing the cron daemon’s special @reboot directive.
How to Configure the crontab for Startup Scripts
The cron daemon is traditionally used for scheduling recurring tasks based on time (e.g., every Tuesday at 3 AM). However, the @reboot flag instructs cron to execute the command exactly once, immediately after the cron service itself starts during the boot sequence.
- Open your Linux terminal.
- Determine the absolute path to the shell script you want to run (e.g.,
/home/user/scripts/start_server.sh). - Ensure the script is executable by running:
chmod +x /home/user/scripts/start_server.sh - To edit your user’s crontab file, run:
crontab -e(If you need the script to run with root privileges, runsudo crontab -einstead). - Scroll to the very bottom of the file.
- Add the following line:
@reboot /home/user/scripts/start_server.sh - Save the file and exit your text editor.
How to Handle Scripts That Depend on Network Connectivity
A common issue with @reboot is that the cron daemon starts very early in the Linux boot sequence, often before the network interfaces have finished initializing. If your shell script attempts to ping an external server, download a file via curl, or mount a network share, it will instantly fail because the internet is not yet available.
To fix this, you must introduce a deliberate delay into your crontab command, forcing cron to wait before executing your script. Modify your crontab entry to look like this:
@reboot sleep 30 && /home/user/scripts/start_server.sh
This command tells the system to pause for 30 seconds after booting, giving the networking stack plenty of time to come online, before finally executing your custom shell script.