Search code examples
bashshellgnu-screeninotifywait

Restart a crashed screen


I have a simple bash script, which uses the inotifywait command and based on the modification that is done, it run a rsync command. This is done in an infinite loop.

The script is run in a "screen" session, but unfortunately it crashes from time to time (no error as to why).

I've been searching for a way to "monitor" that specific screen/script and restart it when it crashes, but I'm struggling to find a solution to that.

The script is run "screen -AmdS script ./script.sh".

Script example:

#!/usr/bin/bash
while inotifywait --exclude "(.log)" -r -e modify,create,delete /home/backups/
do
rsync -avz -e --update --rsh='ssh -pxxxxx' /home/backups/* user@target:/location/ --delete --force
done

So my question basically is, is there a way to monitor the 'screen' session and if it stops to start a new one or is there another way to keep this script running constantly and restart it (possibly not utilizing screen).


Solution

  • You can rerun your failing script in a loop until it succeeds. You can do this with

    screen -AmdS script bash -c 'until ./script.sh; do echo "Crashed with exit code $?. Restaring."; sleep 1; done'
    

    Every time your script fails, this will print that your script crashed and what exit code it had, pause for 1 second, and then rerun your script. As soon as your script succeeds (i.e., ./script.sh terminates with a non-zero exit code), then the loop will terminate.

    Note that if your script never succeeds, this is an infinite loop.