Ubuntu – Re-run an application script when it crashes

bashscripts

I have some applications that need to run on my laptop all the time.

I use a bash script to start these applications. In my script I have a loop that looks similar to this:

while true;
do
    xterm
done

This runs an application (xterm in this case) and if the application crashes, the loop starts it again.

This has a disadvantage that there is no "clean" exit from this loop. So even if the intention of the user is to close xterm, the loop starts it again.

Is there a way to start an application from bash script, watch whether it is running, to re-run it if script crashed or do nothing if the user closed it properly ?

Best Answer

Try this:

while true; do xterm && break; done

Applications have exit status codes so that if something exits fine it returns zero... And if something went wrong, it throws out another number. This allows people to hook in and find out the exact issue. This is what the other answer is doing.

&& just checks that the previous command was a zero-status exit and if it was, breaks the loop. If it crashes, it'll throw out something other than 0 and the && ... clause won't trigger; it'll simply loop back around and run xterm.

Related Question