We will explore four ways to add a command or script to run automatically on startup in Linux. These methods are applicable to various Linux distributions and can be used with any programming language or system command. Ensure that you use the full path for everything and grant execution privileges to your script (chmod +x).
1. Create a new cron task
Cron is a service that automatically starts on boot, allowing users to execute scheduled commands. The crontab file lists commands and their start times in a format understood by the cron service. To add a script on startup using crontab, follow these steps:
-
Open a terminal.
-
Edit the crontab file:
crontab -e
-
If it's your first time, select an editor (press Enter for Nano).
-
Add a new line starting with @reboot followed by the full path to your script:
@reboot /home/user/script.sh
-
Save and exit (CTRL+O, CTRL+X with Nano).
Note: For tasks requiring administrator privileges, use sudo crontab -e instead.
2. Use Startup Applications Preferences (GNOME Desktop)
On Ubuntu and other distributions with GNOME desktop, you can use the "Startup Applications Preferences" tool to run a script or application on startup.
- Open the main menu and find the "Startup Applications Preferences" icon.
- Click "Add" to add a new startup program.
- Fill in the form with the script name and the full command to start it (e.g.,
/home/user/script.sh).
- Click "Add" to save it.
3. Edit rc.local
The rc.local method allows you to run a script on startup by editing the rc.local file, which is executed at the end of the multi-user run level.
-
Open the rc.local file with Nano:
sudo nano /etc/rc.local
-
If the file doesn't exist, create it with the following structure:
#!/bin/bash
exit 0
-
Add your script just before the "exit 0" line, save, and exit (CTRL+X).
-
Grant execution privileges:
sudo chmod +x /etc/rc.local
4. Create a new file in /etc/init.d
This method is best suited for service-like scripts (e.g., firewall script).
-
Create a new file in /etc/init.d:
sudo nano /etc/init.d/myservice
-
Paste the following lines (modify as needed):
#!/bin/bash
### BEGIN INIT INFO
# Provides: MyService
# Required-Start: $all
# Required-Stop:
# Default-Start: 5
# Default-Stop: 6
# Short-Description: Your service description
### END INIT INFO
/home/user/script.sh
-
Save your file and exit (CTRL+X).
-
Add execution permissions:
sudo chmod +x /etc/init.d/myservice
-
Inform the system to start it on boot:
sudo update-rc.d myservice defaults
Reboot to check if your script runs automatically on startup.