Run script at start on debian

Using Debian, there are a few ways to automatically run a script when your system starts up. The following illustrates how to do so at the system level on boot. There are other ways to run scripts in other scenarios for example, when you login.

I run a straight debian install, but the following should also work for all debian based systems such as Ubuntu or Crunchbang.

Run script on system boot

First you need to create the script to run, here is a template, modify the example commands in the start and stop sections.

#! /bin/sh

# Provides:          foobar
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: foobar
# Description:       more foo for your bars

# Carry out specific functions when asked to by the system
case "$1" in
    echo "Starting foobar "
    # example 1 - system service
    # /usr/bin/foobar --config /etc/foo.conf start

    # example 2 - run script as user
    # su --login mkaz --command "/home/mkaz/bin/my-script --cmd-args"
    echo "Stopping foobar"
    # example 1
    # /usr/bin/foobar --config /etc/foo.conf stop

    echo "Usage: /etc/init.d/foobar {start|stop}"
    exit 1

exit 0

Save this file and move to /etc/init.d for example if I named my file foobar

sudo mv foobar /etc/init.d/       # move to init.d
sudo chmod 755 /etc/init.d/foobar # make executable

The way linux runs script is it goes through different run levels and runs the scripts for each level. You can see these in the run level directories ls /etc/rc*. There exist links to each script to run at what level.

You could manually create the proper links to your new script, or there is a convenience script update-rc.d which is much easier. To create the links:

sudo update-rc.d foobar defaults  

If you wish to remove the links, this still keeps the script:

sudo update-rc.d -f foobar remove

Once added you can test starting your service using:

sudo service foobar start

Error or Issue

If you see this warning

insserv: warning: script 'foobar' missing LSB tags and overrides

You probably did not includ the INIT INFO block, see template above. Your script will still run, just does not have the dependency info used by insserv program to try to start items in proper order.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s