With a modern init system (like systemd or upstart), you could just have the init system take care of restarting the script if it fails.
If for some reason you're stuck with a legacy system, you could have the script periodically update a flag file (
touch /var/lib/myapp/flagfile), and then via cron check if the flag file is older than a certain number of seconds, and restart the script if necessary. Something like:
# get current time (in seconds since the epoch)
# get flag file mtime (in seconds since the epoch)
last_update=$(stat --printf '%Y' /var/lib/myapp/flagfile)
if [ $(( now - last_update )) -gt $interval ]; then
If you have systemd available, you just simply create a
.service. unit with theRestart=always
key, which instructs systemd to restart the script whenever it fails. E.g., put something like this in/etc/systemd/system/myscript.service`:
Description=This is my nifty service.
# Put any dependencies here
And then activate it with:
# systemctl enable myscript
# systemctl start myscript
Instead of running a persistent script, you could just run a regular cron job that would perform any necessary checks and remediation. You would be limited to checking once per minute, but if that frequency is acceptable it's probably a simpler solution.