0

I have a shell script that runs a loop 10 times, on each loop the program does the following:

echo "Hello $i times"
sleep 1s

I would like to have another shell script that reads the stdout of the previous shell script, and kills the process when it reads Hello 5 times. Obviously this isn't the final use case, but it's an example. Other partial solutions I've seen can kill the process after it matches the string, but I can't see the output - the entire process is silent - which is undesirable.

Any help would be much appreciated!

1 Answers1

0

If you are using a basic bash script grep -q will send a sigpipe, which should be sufficient to end it.

As far as seeing the output along the way, you can split the stream with tee into your terminal.

# cat loop.sh

#!/bin/bash

for i in {1..1000}
do
    echo "Hello $i times"
    sleep 1s
done


# ./loop.sh | tee /dev/tty | grep -q "Hello 5 times"
Hello 1 times
Hello 2 times
Hello 3 times
Hello 4 times
Hello 5 times
#
vhoang
  • 1,349
  • 1
  • 8
  • 9
  • Use stdout>file if you want to seperate the watchdog part from the execution part (e.g. for multiple watchdogs) and then watch the file content: `unbuffer your_cmd.sh > .tmp_check.txt &` and `tail -f .tmp_check.txt | sed '/termination_phrase/ q'` – Oliver Zendel Oct 18 '21 at 07:38