Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Script Monitor Program for Specific Output

Tags:

bash

scripting

So this is probably an easy question, but I am not much of a bash programmer and I haven't been able to figure this out.

We have a closed source program that calls a subprogram which runs until it exits, at which point the program will call the subprogram again. This repeats indefinitely.

Unfortunately the main program will sometimes spontaneously (and repeatedly) fail to call the subprogram after a random period of time. The eventual solution is to contact the original developers to get support, but in the meantime we need a quick hotfix for the issue.

I'm trying to write a bash script that will monitor the output of the program and when it sees a specific string, it will restart the machine (the program will run again automatically on boot). The bash script needs to pass all standard output through to the screen up until it sees the specific string. The program also needs to continue to handle user input.

I have tried the following with limited success:

./program1 | ./watcher.sh

watcher.sh is basically just 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 OK, but leading whitespace is stripped on the echo statement, and the echo output hangs in the middle until subprogram exits, at which point the rest of the output is printed to the screen. Is there a better way to accomplish what I need to do?

Thanks in advance.

like image 920
Mynock Avatar asked Sep 06 '11 18:09

Mynock


1 Answers

I would do something along the lines of:

stdbuf -o0 ./program1 | grep --line-buffered "some string" | (read && reboot)
like image 113
a3nm Avatar answered Oct 13 '22 07:10

a3nm