I have a bash script that users while do along with sleep to constantly monitor the connection state and take measures in case something goes wrong. The only thing that is not guarded is the execution of the checking script itself.

I'd like to have the myscript.sh executed at startup via init.d entry and then have CRON task executed every minute to see if the script that I ran at startup automatically is still executing. How can I achieve this?


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)
now=$(date +%s)

# 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

Using systemd

If you have systemd available, you just simply create a .service. unit with theRestart=alwayskey, 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

Using cron

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.

  • Cool, thanks. Even though this is an answer already, I would much appreciate you writing a passage about how to get a failed script restarted via upstart or systemd since I have both available, it's Debian 7 in question. Aug 11 '15 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.