Home > Blockchain >  Run a Bash script if not Running
Run a Bash script if not Running

Time:12-24

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?

CodePudding user response:

I would take a look at Cron. It's a way to automate a script to run on a schedule. Almost every Linux machine has Crontab, so it shouldn't be hard to get started with a couple of examples.

CodePudding user response:

Your goal is exactly the feature 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=.

  • Related