How to run a Raspberry Pi Program at Boot
Tutorial: How to run a program from boot
Having a program start by itself when you boot your Raspberry Pi can be very useful. There are a few ways of running a command at start-up, but in this tutorial we will create a script within etc/init.d so that when the system boots the program will start/stop automatically on boot/shut-down.
For the purpose of this tutorial we will show you the method for an arbitrary program created in python 'example.py' with its location /home/pi/example.py. The following code will work for any script, just replace 'example' with name of your program and replace /home/pi/example.py to wherever you are actually keeping your script.
First we need to create a script within /etc/init.d/. Type the following command in the terminal but replace 'example' with the name of your own program:
sudo nano /etc/init.d/example
This will open a text editor. Paste the following code into here and replace the name and location of the program with your own. The parts in black are the ones you'll need to change:
#! /bin/sh
# /etc/init.d/example
### BEGIN INIT INFO
# Provides: example
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start a program from boot
# Description: A simple script which will start a program from boot and stop upon shut-down
### END INIT INFO
# Put any commands you always want to run here.
case "$1" in
start)
echo "Starting example"
# run the program you want to start
/home/pi/example.py
;;
stop)
echo "Stopping example"
# end the program you want to stop
killall example.py
;;
*)
echo "Usage: /etc/init.d/example {start|stop}"
exit 1
;;
esac
Once you've copied the above code and replaced the names with that of your own exit and save with Ctrl+X.
Next you need to make the program executable:
sudo chmod +x /etc/init.d/example
Check the program is working correctly from etc/init.d/example by test starting it:
sudo /etc/init.d/example start
And the same again test stop the program:
sudo /etc/init.d/example stop
Next we need to register the program with the system so it knows to run/stop the program at boot/shutdown.
sudo update-rc.d example default
And that's it! Now you can reboot your Raspberry Pi and the program 'example' should start up automatically.
If you ever wish to stop the program running from boot type the following command:
sudo update-rc.d -f example remove