Monday, September 2, 2013

Running scripts on ubuntu startup

When we work on embedded systems it is often required to run certain programs/scripts on OS boot. For example, while I was working on viSparsh (a haptic belt for the visually impaired), the belt boots Ubuntu and it needs to power Kinect and start retrieving data. It shall simultaneously process the data and find the potential obstacles and notify user with intensity varied stereo-vibrations.

Ubuntu has a concept of runlevels where you can set up your preference for a script for the level in which you want it to execute. Below are the ways of executing scripts on either startup or shutdown-

To execute a script upon rebooting Ubuntu

  • Put your script in /etc/init.d and then create softlinnks to any of the run level
  • ln -s /etc/init.d/autorunScript /etc/rc2.d/S99autorunScript command will create a softlink of autorunScript in runlevel 2 with a execution priority of 99. SXX denotes Startup and with priority XX (where 01 < XX < 99).  
  • Make sure the script autorunScript is executable (sudo chmod +x autorunScript)
  • Note: The scripts in this directory are executed in alphabetical order

To execute a script at startup of Ubuntu

  • Edit /etc/rc.local and add your commands
  • The script must always end with exit 0
  • The scripts/commands in this file are executed after all the runlevels

To execute a script at shutdown

  • Put your script in /etc/init.d
  • ln -s /etc/init.d/autorunScript /etc/rc6.d/K98autorunScript command will create a softlink of autorunScript in runlevel 6 with a execution priority of 98. KXX denotes Shutdown and with priority XX (where 01 < XX < 99).  
  • Create softlink of your script in /etc/rc6.d
  • Make it executable (sudo chmod +x myscript)
  • Note: The scripts in this directory are executed in alphabetical order


It is often very convenient to write your commands directly into /etc/rc.local and if you are executing any scripts put those scripts into /home folder to avoid execution permission issues. In case there are multiple scripts to be run make them background process if it is not a UI application. To run a script as a background process simply put an ampersand (&) at the end of the command.

No comments:

Post a Comment