Raspberry Pi Startup Script
--
Syncs your raspberry pi with a remote git repository and launches a flask app on boot to incorporate remote changes.
I couldn’t find a simple guide on how to have a Raspberry Pi sync with a remote repository and run a script on startup so I decided to write one. I use this to have the Raspberry Pi pull the latest from a GitHub repository and then run a python script. This means that each time the Pi starts up it incorporates any changes that were made since its previous runtime.
This example launches a simple flask app on startup.
Edit crontab:
sudo crontab -e
Add command at end of file:
@reboot rm -rf /root/Pi_Startup_Example && git clone https://github.com/jack-alope/Pi_Startup_Example.git /root/Pi_Startup_Example && python3 -m pip install -r /root/Pi_Startup_Example/requirements.txt && python3 /root/Pi_Startup_Example/app.py &
Reboot and verify it worked by checking http: //ip-of-pi:5000
That’s it.
What does that do?
Cron is used to schedule commands in unix-like operating systems. In this case we are using the @reboot tag to schedule a command on reboot. This command could be anything. If you wanted it to run a script you have stored on the machine it would simply look like:
@reboot /path/to/script
In my case I want it to sync with a remote repository and then run a command. The easiest way I found to do this is to
Remove the existing directory (if it exists)
rm -rf /root/Pi_Startup_Example
Clone the remote repository
git clone https://github.com/jack-alope/Pi_Startup_Example.git /root/Pi_Startup_Example
Install Requirements
python3 -m pip install -r /root/Pi_Startup_Example/requirements.txt
* If your requirements are not changing you can leave this part out.
Run the desired script
python3 /root/Pi_Startup_Example/app.py
These are all chained together into a single command using && to create the command shown above. The trailing & means that the command runs in the background while the Pi continues to startup.
Warnings
If this does not work for you it may be because of one of these issues.
- Pi must be connected to internet. Ethernet is most reliable.
- Since this is running at startup if you require certain libraries or commands it may run before those libraries are loaded.
- Permissions. It may be required to prefix the script with
sudo
depending on what your script does.