Wednesday, 18 May 2011

Run your script on system startup

Sometime you want to auto mount your window partitions on your linux machine or sometime you find need to clean clear or purge your database/inbox or sometime you might want to run your own custom script. Reasons are many and so are the solutions.

1) use cron jobs
2) use linux run level file

Cron Jobs are good. It'll help you to run your script after certain interval or at a specific point of time.
It can be used to clear your site cache at the end of week OR purge my logs after every 5 hour or Send me an email on 23 march , 2011 at 12:00 noon. etc etc.

Run Level files :
Linux run level find help you to run your script/daemon at different run level of system.
You can find more info on run level on this nice link.

Coming to execution of a script on startup.

linux have many run level files. In ubuntu if you ls your /etc dir you'll find differnt run levels files/dir on your system.
 On ubuntu :
root@dragonaider:/home/sahilsk# ls /etc/ | grep "^rc"
rc0.d
rc1.d
rc2.d
rc3.d
rc4.d
rc5.d
rc6.d
rc.local
rcS.d

In ubuntu rc0...6 are differnt run level directory, each of which contain script executing at different run levels i.e each needed different system resources and privileges .
rc.local file  specify the script to be executed after every other run level files finished executing.
You can invoke any run level by simple typing "init" followed by runlevel e.g.
$init 6 
WARNING: it will reboot your system. :P
So, you've a script you want to run it on startup, but on which run level should i place my script??
if your script dont' demand system reboot or start just  add it in rc.local file. 
OR 
you can make use of update-rc.d utility to add entry for your file in different run level .
eg. MY script name "startup.sh"
I put my script in /etc/init.d/ dir. And then i run "udate-rc.d  myScriptName  defaults"
            
root@dragonaider:/home/sahilsk# update-rc.d startup.sh defaults
update-rc.d: warning: /etc/init.d/startup.sh missing LSB information
update-rc.d: see <http://wiki.debian.org/LSBInitScripts>
 Adding system startup for /etc/init.d/startup.sh ...
   /etc/rc0.d/K20startup.sh -> ../init.d/startup.sh
   /etc/rc1.d/K20startup.sh -> ../init.d/startup.sh
   /etc/rc6.d/K20startup.sh -> ../init.d/startup.sh
   /etc/rc2.d/S20startup.sh -> ../init.d/startup.sh
   /etc/rc3.d/S20startup.sh -> ../init.d/startup.sh
   /etc/rc4.d/S20startup.sh -> ../init.d/startup.sh
   /etc/rc5.d/S20startup.sh -> ../init.d/startup.sh

As you can see, update-rc.d has create a record of my script in each run level file.
Learn more on update-rc.d command at this link.

No comments:

Post a Comment