Menu
User

DropVPS Team

Writer: Cooper Reagan

How to make a script run at startup linux?

How to make a script run at startup linux?

Publication Date

05/03/2025

Category

Articles

Reading Time

2 Min

Table of Contents

If you’re managing a Linux server or desktop environment, you might find yourself needing to run specific scripts automatically at startup. Whether it’s for setting up your environment, starting services, or running maintenance tasks, automating these processes can save you time and effort. In this article, we’ll explore different methods to achieve this in Linux.

Method 1: Using Systemd

Most modern Linux distributions use systemd to manage services and system processes. To create a startup script using systemd, follow these steps:

  1. Create Your Script: Write your script and save it in a directory, for example, /usr/local/bin/myscript.sh. Make sure it’s executable:

    #!/bin/bash
    echo "Hello, World!" > /tmp/hello.txt

    Then, make it executable:

    chmod +x /usr/local/bin/myscript.sh
  2. Create a Systemd Service File: Create a service file in /etc/systemd/system/. You can name it myscript.service:
    sudo nano /etc/systemd/system/myscript.service

    Add the following content:

    [Unit]
    Description=My Startup Script
    
    [Service]
    ExecStart=/usr/local/bin/myscript.sh
    
    [Install]
    WantedBy=multi-user.target
  3. Enable the Service: Now, enable your service so that it starts at boot:

    sudo systemctl enable myscript.service
  4. Start the Service: You can also start it manually without rebooting:

    sudo systemctl start myscript.service

Method 2: Using Cron Jobs

Another way to run scripts at startup is through cron, specifically using the @reboot directive.

  1. Edit the Crontab: Open the crontab for editing:

    crontab -e
  2. Add Your Script: At the bottom of the file, add the following line:
    @reboot /usr/local/bin/myscript.sh

    This will execute your script every time the system boots.

Method 3: Using rc.local

If you’re using an older version of Linux or a distribution that still supports rc.local, you can add your script to this file.

  1. Edit rc.local: Open the rc.local file for editing:

    sudo nano /etc/rc.local
  2. Add Your Script: Before the exit 0 line, add:

    /usr/local/bin/myscript.sh &
  3. Make rc.local Executable: Ensure that rc.local is executable:

    sudo chmod +x /etc/rc.local

Conclusion

By following these methods, you can easily set up your scripts to run at startup on a Linux system. Whether you choose systemd, cron, or rc.local, each method has its benefits depending on your specific needs and the Linux distribution you are using.

Linux VPS
U
Loading...

Related Posts