Automatically run a programme on boot up

The file located at /etc/rc.local can be used to run commands on bootup. Programs can be run with either root privileges or as other users. To edit this file, type:

sudo nano /etc/rc.local

The file will look something like this. Commands placed just above the ‘exit 0’ will be run on startup. Highlighted below in yellow you can see that I’ve added some lines. The first runs a python programme which will be run with root privileges. The second runs a shell script as user ‘fred’ with freds privileges.

  • #        are comment lines which are ignored by the operating system.
  • &        at the end of my added line makes the process/program run in the background so that the boot process can continue without waiting for the python script to finish. This is especially important if the script contains an inifinite loop and doesn’t exit as the pi would not complete booting up.

#!/bin/sh -e
# rc.local
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will
“exit 0” on success or any other
# value on error.
# In order to enable or disable this script just change the execution
# bits.
# By default this script does nothing.
# Print the IP address

_IP=$(hostname -I) || true
if [ “$_IP” ]; then
printf “My IP address is %s\n” “$_IP”

#run python program with root privileges
/home/pi/ &

#run maintenance script as user ‘fred’
sudo -u fred /home/fred/ &

exit 0

You may wish to have the programmes write their output to a file so that you can check for errors, etc. To do this you can add >> /directory/log_filename 2>&1 after the filename like so:

sudo -u fred /home/fred/ >> /tmp/maint.log 2>&1 &

To understand how this works, we need to read it from right to left:

  • 2>&1        The 1 stands for ‘File Descriptor 1’ (The normal output i.e. what you see on screen). The 2 stands for ‘File Descriptor 2’ (The standard error output). So 2>&1 redirects the error output to the normal output i.e, we now have both output going to the same place. It needs to be 2>&1 rather than 2>1 because otherwise it would try and write it out to a file named 1 – in this context the & sign means it’s a File Descriptor.
  • >> /tmp/maint.log        redirects the standard output to a file named /tmp/maint.log. (>> means append, > means overwrite).
  • /tmp/maint.log        This is the location to write the output to. I recommend writing to a file in the /tmp directory as all users have read/write access to it and it is cleared out on every bootup. Don’t use this location if the log file is going to contain something you don’t want others to see, or if you need to keep the file after a reboot.

Leave a Reply

Your e-mail address will not be published. Required fields are marked *