How to Automatically Start a Script on Linux
Ohidur Rahman Bappy
MAR 22, 2025
How to Automatically Start a Script on Linux
Running scripts automatically at boot is a common task. Here are four ways to achieve this on Linux:
1. Use the Crontab
One of the simplest methods to start a script at boot is using the crontab with the @reboot
option.
Steps:
- Open a terminal
- Edit the crontab file:
If it's your first time, you need to select an editor (press Enter for nano).crontab -e
- Add a line to start your script at boot:
@reboot /home/pi/Desktop/test.sh
- Save and exit (CTRL+O, CTRL+X with nano).
This schedules your task to start at each boot.
2. Place Your Script in /etc/init.d
For scripts that function like services, placing them in /etc/init.d
might be preferred.
Steps:
- Create a new script file:
sudo nano /etc/init.d/myservice
- Add the following content:
#!/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 touch /home/pi/myservice_test
- Save and exit (CTRL+X).
- Make your script executable:
sudo chmod +x /etc/init.d/myservice
- Register the script to run at boot:
sudo update-rc.d myservice defaults
3. Create an Upstart Job
Another option is to create an upstart job, though this might not be available on all Linux distributions.
Steps:
- Create a configuration file:
sudo nano /etc/init/myjob.conf
- Add the following content:
description "my job" start on startup task exec /home/pi/Desktop/test.sh
Simply creating this file enables the script to run at each boot.
4. Add a Line in /etc/rc.local
Using /etc/rc.local
is perhaps the simplest way to start scripts.
Steps:
- Open the rc.local file:
sudo nano /etc/rc.local
- Add your script before
exit 0
:/home/pi/Desktop/test.sh
- Save and exit (CTRL+X).
Reboot to see if it starts as expected.
Determine the Command to Start
Before automating, know the command to run. If it's a script, use its path. For other programs, determine where they're installed:
Find the Path
- Use the
which
command:which <COMMAND>
- If that fails, use the
find
command:sudo find / -iname <PROGRAM_NAME>
Graphical Programs
- Navigate in the main menu to Properties to see the command used.
By following these methods, you can efficiently automate the startup of any script or application on your Linux system.