Search code examples
linuxbashscriptingraspberry-piautomated-tests

Run a Bash script if not Running


I have bash script sitting on linux device in the field. I want this script to be running 24/7. There are sometime just bad instances when my script would break because of reason not in my control. So, in that case I want this script to restart whenever it dies.

Any ideas or example code to get me going?


Solution

  • Your goal is exactly the function of a service manager, and systemd is the one that comes with Raspbian. You can create a systemd service for your script, set its restart mode to always (can only be stopped manually) or on-failure (restart when exits with failure).

    You can create /etc/systemd/system/my-script.service with the following content:

    [Unit]
    Description=My Script
    
    [Service]
    Type=simple
    ExecStart=/bin/bash /path/to/script.sh
    #WorkingDirectory=somewhere if you need
    Restart=on-failure
    RestartSec=2
    
    [Install]
    WantedBy=multi-user.target
    

    You then run systemctl daemon-reload and systemctl start my-script.

    If you need more customization, you can look up the manual page near Restart=.