How to Run a Script at Boot on Raspberry Pi

Raspberry Pi Tutorial
(Image credit: Tom's Hardware)

There are a lot of reasons you’d want to run a Python script, an app or another type of script (ex: a Bash script) every time your Raspberry Pi boots up. Perhaps you have a robot or IoT device that has to be ready to perform a task as soon as the Raspberry Pi powering it starts up. Or maybe you just want to have a particular program running in the background at all times and don’t want to have to launch it manually at every session.

There are a number of ways to automatically start a script at Raspberry Pi bootup, but the easiest is to use crontab, a scheduling feature that also lets you set scripts to run at particular times.

Latest Videos FromTom's Hardware
Avram Piltch
Managing Editor: Special Projects

Avram Piltch is Managing Editor: Special Projects. When he's not playing with the latest gadgets at work or putting on VR helmets at trade shows, you'll find him rooting his phone, taking apart his PC, or coding plugins. With his technical knowledge and passion for testing, Avram developed many real-world benchmarks, including our laptop battery test.

  • bit_user
    In fairness, I didn't know crontab had @reboot. However, I wonder if it can distinguish between a real reboot and the cron daemon simply getting restarted. Probably doesn't matter... just a thought.

    What if you want to stop your autorunning script after your Raspberry Pi has booted? If your script has already completed running, it will be gone from memory but if it’s designed to do something continuously, you’ll need to search for and kill the task.
    That's when you really ought to consider making it a service. See:
    https://www.raspberrypi.org/forums/viewtopic.php?t=266701https://domoticproject.com/creating-raspberry-pi-service/Anyway, on killing a process...
    1. Search for your script by using the ps aux command and putting the name of your script (or at least a partial name) after grep.

    ...

    2. Kill each process number using the sudo kill -9 command.

    You can do it in just one step, using the killall command. Just be sure your script is named uniquely, and that you really want to kill all instances of it.


    Probably should also mention something about signals and how it's sometimes with trying SIGINT or SIGTERM, before reaching for SIGKILL.
    Reply