To run a .sh file automatically after every restart or reboot on Ubuntu, you can use the cron
scheduler or create a systemd service.
Method 1: Using cron scheduler
1. Open a terminal window.
2. Type crontab -e
and press Enter. This will open the crontab file in the default text editor.
3. If it asks you to choose an editor, select your preferred editor (e.g., nano, vi).
4. In the crontab file, add the following line to run the .sh file at startup:
@reboot /path/to/your/script.sh
Replace /path/to/your/script.sh
with the actual path to your .sh file.
5. Save the file and exit the text editor.
6. The .sh file will now be executed automatically after every reboot.
Method 2: Using systemd service
Create a new systemd service unit file. Open a terminal window and enter the following command to create the file:
sudo nano /etc/systemd/system/my-script.service
In the editor, add the following lines to the my-script.service file:
[Unit]
Description=My Script
After=network.target
[Service]
ExecStart=/path/to/your/script.sh
[Install]
WantedBy=default.target
Replace /path/to/your/script.sh
with the actual path to your .sh file.
Save the file and exit the text editor.
To enable the service to run at startup, enter the following command:
sudo systemctl enable my-script.service
Restart your system, and the .sh file will be executed automatically.
Note: Make sure your .sh file has executable permissions (chmod +x script.sh
) to ensure it can be executed.
Choose the method that suits your requirements best and follow the corresponding steps to run your .sh file after every restart or reboot on Ubuntu.