logo

How to Automatically Start a Script on Linux

O

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:

  1. Open a terminal
  2. Edit the crontab file:
    crontab -e
    
    If it's your first time, you need to select an editor (press Enter for nano).
  3. Add a line to start your script at boot:
    @reboot /home/pi/Desktop/test.sh
    
  4. 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:

  1. Create a new script file:
    sudo nano /etc/init.d/myservice
    
  2. 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
    
  3. Save and exit (CTRL+X).
  4. Make your script executable:
    sudo chmod +x /etc/init.d/myservice
    
  5. 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:

  1. Create a configuration file:
    sudo nano /etc/init/myjob.conf
    
  2. 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:

  1. Open the rc.local file:
    sudo nano /etc/rc.local
    
  2. Add your script before exit 0:
    /home/pi/Desktop/test.sh
    
  3. 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.