You already know how to run scripts periodically with a cron job if you read my last blogpost about the Raspberry Pi. This time i will explain how to run scripts on startup. Because you do want to restart your Minecraft server when the Raspberry Pi crashes, right? 😉
There are several ways to create startup scripts, I will only explain the easiest and most common one.
This is not a folder, but a file that will get run whenver you boot/reboot your Raspberry Pi. So let’s open that file with our beloved nano editor:
sudo nano /etc/rc.local
Whatever you add to that file, make sure to add it BEFORE “exit 0“. That one should always be the very last line. You do not need to add “sudo” to the calls, because all commands will get called as root user. One more important thing to know is that you need to use the full path, because environmental variables are not set when those commands will get called.
So this is what it would look like if you would want to call a python script on startup:
By default there already are some lines of code in the file, so this is what the whole file looks like with the python script call:
# 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
# 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"
…and that’s pretty much all there is to know. Next time your Raspberry Pi boots, the script will get executed. You can also call your own shell scripts:
Just make sure to make them executable by using chmod +x, as explained in the article about Cron Jobs. The Ampersand (“&”) means that the start script will not wait for the script and go to the next line immediately.
One more important thing to know is how to log errors. Make sure rc.local works correctly BEFORE you reboot your Raspberry Pi, you can do that by just calling it directly in the shell:
This is the best way to check if your entries worked and to see if there are any errors.
That´s it about startup scripts so far, if you got any questions or tips, feel free to comment!