Home > Enterprise >  run program when a command's output changes in bash
run program when a command's output changes in bash

Time:11-20

For example lets say there is a program called foo and the program prints a new line whenever it wants. How can i run another program when foo prints a new line?

foo example:

while true; do
    echo hi
    sleep 1
done

i cant edit foo

CodePudding user response:

Here is a function that I think will serve your purpose:

function my_function { while true; do read && "$@" ; done ; }

To run a program prog every time a program foo prints out a line, you can write this at the terminal:

foo | my_function prog

If you want to pass arg1 and arg2 as arguments to "prog", you can call it like so (thank you @Ulrich Eckhardt and @glenn jackman):

foo | my_function prog arg1 arg2

CodePudding user response:

As already suggested in comments, you can use while read to perform a loop iteration for each line of output from foo.

foo |
while IFS= read -r line; do
    # maybe echo "$line"?
    echo "hi"
done

There are options to read to allow for a different input separator than newline.

This could be simplified a lot if you only really care about doing something when a line arrives, but not about the actual output before the newline. The -r option and the IFS= assignment help preserve the precise contents of line inside the loop (specifically, IFS= prevents the shell from trimming whitespace from the input value, and the -r option disables parsing of backslashes, which you generally don't want).

  •  Tags:  
  • bash
  • Related