How to execute bash script at upstart

How to execute bash script at upstart

October 29,2015 by fzfatima

How to execute bash script at upstart

In this tutorial, we will learn how to execute a bash script at upstart.

What is Upstart?

Upstart is an event-based replacement for the /sbin/init daemon which handles starting of tasks and services during boot, stopping them during shutdown and supervising them while the system is running.

Commands

Create a Job in /etc/init.

sudo gedit /etc/init/sync_user.conf

Job configuration files are named as <name>.conf

Add the following lines to sync_user.conf

start on filesystem and net-device-up IFACE!=lo
  stop on runlevel [016]

script
  exec bash -c 'path_to_bash_script_file/file_name start'
end script

To ensure that you haven't misused the Upstart syntax, use the init-checkconf command:

init-checkconf sync_user.conf

Then start the job

sudo start sync_user

Understating the code

Start on condition:

start on filesystem and net-device-up IFACE=lo

Job will be started when the filesystem is mounted and net-device-up IFACE=lo event, which signifies the local network (for example, 127.0.0.0 for IPv4) is available.

Stop on conditon:

stop on runlevel [016]

This ensures the job will be stopped on shutdown[0], when switching to single-user mode[1] and on reboot[6].

Runlevels for Debian and Ubuntu systems are generally as follows:

  0 : System halt.
  1 : Single-User mode.
  2 : Graphical multi-user plus networking (DEFAULT)
  3 : Same as "2", but not used.
  4 : Same as "2", but not used.
  5 : Same as "2", but not used.
  6 : System reboot.

Script

All job files must have either an exec or script stanza. This specifies what will be run for the job.

script
  exec bash -c '/opt/local/our-sync-pkg-2.0/sync_users start'
end script

exec gives the path to a binary on the filesystem and optional arguments to pass to it.

Executing bash script

By default, Upstart uses "/bin/sh" to execute script sections. You can change the default shell.

But it can done in simplest way by executing this line:

exec bash -c '/opt/local/our-sync-pkg-2.0/sync_users start'

bashin exec is used because we're executing the bash script.

-c option after bash means that commands are read from string.

end script will terminate the script.

This will work! If you have any suggestions on improving this post, let me know.