Run a shell script at startup / reboot

This post introduces how to auto run a shell script when your machine reboot.

We can set a crontab for this.

The crontab (short for “cron table”) is a list of commands that are scheduled to run at regular time intervals on your computer system. The crontab command opens the crontab for editing, and lets you add, remove, or modify scheduled tasks.

Just have a line added to your crontab.

Make sure the sh file is executable (you can use the following command to make the file executable)

$ chmod +x /path_to_you_file/your_file

To edit crontab file, enter the following command in your terminal:

$ crontab -e
# Edit your crontab.

The line you need to add:

@reboot  /path_to_you_file/your_file

for example,

@reboot  /home/user/test.sh

after every startup it will run the test.sh script.

To save and exit your crontab from vim,

 

Use the following command to confirm that it is actually been set.

$ crontab -l
# Display ("list") the contents of your crontab.

this will show @reboot sh $HOME/test.sh

To see whether the app that the .sh starts is actually running, you can use ps -ef (check here for more details about ps -ef).

Reboot the server to confirm whether it all works.

References:

Linux crontab command (PDF)

Linux at, batch, atq, and atrm commands (PDF)

How to run a shell script at startup (PDF)

Leave a Reply

Your email address will not be published. Required fields are marked *