1

In bash, I have a command running in screen that is effectively:

while true
do
  echo $RANDOM
  sleep 1
done

The output of which is:

12396
19683
31641
...

I'd like to pipe that into something like grep/awk and I match a specific pattern, such as 12345, I want a command to run.

I don't want to capture the full output of the running command - it may run for a very long time before a match is found and I don't want to waste space on the machine.

Can this be done easily in bash?

In an ideal world, I would also like the output the continue to be printed to the terminal, so I can remote in and monitor the output myself, but that's not strictly necessary.

1 Answer 1

1
./feeding_script.sh |
tee >(while read a; do [ "$a" == "12345" ] && </dev/null another_command; done)

Notes:

  • tee splits the data stream; one copy goes to a "file" which is in this case a command >(…), the other continues to the terminal;
  • </dev/null another_command – this redirection prevents another_command from consuming data generated by feeding_script.sh.
2
  • Why is the </dev/null needed, it would share the same stdin as tee? It looks like the while & test would get the input first, but I'm not too sure what happens with process substitutions (or what happens if another_command takes a long time & the feeding_script data backs up)
    – Xen2050
    Dec 28, 2017 at 23:06
  • @Xen2050 If another_command could feed itself from stdin (without redirection) then it would be able to consume any number of lines that follow the triggering 12345. These lines would never go to while read …. I assumed they all should go there and be tested. But if the idea is to detect 12345 as a header that precedes data that should go to another_command, then </dev/null is wrong. Dec 28, 2017 at 23:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .