Table of Contents
What you will read?
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:
-
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.txtThen, make it executable:
chmod +x /usr/local/bin/myscript.sh - Create a Systemd Service File: Create a service file in
/etc/systemd/system/. You can name itmyscript.service:sudo nano /etc/systemd/system/myscript.serviceAdd the following content:
[Unit] Description=My Startup Script [Service] ExecStart=/usr/local/bin/myscript.sh [Install] WantedBy=multi-user.target -
Enable the Service: Now, enable your service so that it starts at boot:
sudo systemctl enable myscript.service -
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.
-
Edit the Crontab: Open the crontab for editing:
crontab -e - Add Your Script: At the bottom of the file, add the following line:
@reboot /usr/local/bin/myscript.shThis 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.
-
Edit rc.local: Open the
rc.localfile for editing:sudo nano /etc/rc.local -
Add Your Script: Before the
exit 0line, add:/usr/local/bin/myscript.sh & -
Make rc.local Executable: Ensure that
rc.localis 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.
