18

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 ?

29

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.

  • 6
    That's quite elegant. – Oli Jan 12 '15 at 14:02
  • Hmm.. The other way around as well: while xterm; do true; done – muru Jan 12 '15 at 14:59
  • 1
    @muru: This works for me: while ! xterm; do :; done – Cyrus Jan 12 '15 at 15:24
  • 1
    @Cyrus Ah, yes. forgot the !. – muru Jan 12 '15 at 15:26
6

In the while condition you can test whether exit status of xterm was successful or not with something like this:

result=1
while [ $result -ne 0 ]; do
    xterm
    result=$?
done

$? variable holds exit status of last executed command.

0

I will suggest you to use.

until xterm ; do echo "program ended with status $?" ; done

This will re-run your program if it is killed.

0

Try use supervisor it very simple and easy to add program or script to run. In you case as minimal you need command and maybe exitcodes in programx-section to configure.

Default exitcodes is 0,2 so it means:

supervisord will restart the process if it exits with an exit code that is not defined in this list

In general it`s that you want: re-run it if script crashed or do nothing if the user closed it properly(or script completed successfuly)

try the simplest configuration first:

[program:you_app_name]
command=/path/to/you/app

To more flexibility see configuration File documentation.

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.