Thursday, November 8, 2012

[Tutorial] Run script at bootup in linux (cronjob or bashscript)



Introduction

If you are lazy programmer like me, you would like to automate everything rather than having to do stuff manually. Usually bash script / python script can become extremely handy getting things done. You can have these scripts to start automatically at bootup or at scheduled time.

Running script/program at bootup under linux environment

In order to run your custom script at bootup under linux environment, you need to copy your script to /etc/init.d/ directory


 cp custom_script.sh /etc/init.d/.


Then you need to change permission to make it executable.


 chmod +x /etc/init.d/custom_script.sh


Create link to your script in rc.d directory.


 ln /etc/init.d/custom_script.sh /etc/rc.d/custom_script.sh


You are all ready to go and your script will be running next time you reboot your computer!

Cron Job


If you want to run your custom script at specific time, then you can use crontab to schedule and automatically run it.

Make sure you have crontab available on your linux machine and edit your crontab file by typing following:


 crontab -e


Crontab syntax is pretty simple. Each line consists of this simple syntax consisting of 6 columns.


 Minute Hour Day Month Week_Day Command


You can specify the script to run every unit (hour, minute etc.) time by using * instead of real number.
Following cron line will run cmd every minute of every hour of every month.


 * * * * * cmd

You can specify the script to run at specific time interval using dash.
For example, following cron line will run the command every weekday between 9 am and 5 pm.

 00 09-17 * * 1-5 cmd



That's it!
Now you can just relax and let the script start automatically.
If you want the script to keep running all the time, you can write a bash script to keep restarting it when it dies.
For more info, look at my another posting here.



No comments: