Bash Script Monitoring program for a specific exit

So this is probably a simple question, but I don't really like the bash programmer, and I could not figure it out.

We have a closed source program that calls a subroutine that runs before it exits, after which the program calls the subroutine again. It repeats endlessly.

Unfortunately, the main program sometimes spontaneously (and repeatedly) cannot call the subprogram after a random period of time. A possible solution is to contact the original developers to get support, but at the same time, we need a quick fix to this problem.

I am trying to write a bash script that will track the output of a program, and when it sees a certain line, it will restart the machine (the program will start automatically at boot). The bash script should go through all the standard output to the screen until it sees a specific line. The program should also continue to process user input.

I have tried the following with limited success:

./program1 | ./watcher.sh 

watcher.sh is basically the following:

 while read line; do echo $line if [$line == "some string"] then #the reboot script works fine ./reboot.sh fi done 

This seems to work fine, but leading spaces are separated by an echo statement, and the echo output hangs in the middle until the subroutine exits, at which point the rest of the output will be printed on the screen. Is there a better way to accomplish what I need to do?

Thanks in advance.

+4
source share
3 answers

I would do something like:

 stdbuf -o0 ./program1 | grep --line-buffered "some string" | (read && reboot) 
+2
source
  • you need to specify your $ line variable, i.e. "$line" for all links * (except for the read line bit).

  • Your program1 is probably the source of the "paused" data. It should flush use its output buffer. You probably are not in control of this, therefore

    a. check if the unbuffer command is available on your system. If yes, try unbuffer cmd1 | watcher unbuffer cmd1 | watcher You may have to experiment with which cmd you wrap unbuffer , you may have to do cmd1 | unbuffer watcher cmd1 | unbuffer watcher .

    b. OR you can try to wrap the observer as a group of processes (I think this is the correct terminology), i.e.

    ./program1 | { ./watcher.sh ; printf "\n" ; }

Hope this helps.

PS as you, it seems, a new user, if you get an answer that helps you remember to mark it as accepted and / or give it + (or -) as a useful answer.

0
source

use the read $REPLY variable, I would also suggest using printf instead of echo

 while read; do printf "%s\n" "$REPLY" # '[[' is Bash, quotes are not necessary # use '[ "$REPLY" == "some string" ]' if in another shell if [[ $REPLY == "some string" ]] then #the reboot script works fine ./reboot.sh fi done 
0
source

All Articles