6

I am taking output of one script, then piping this putput to grep and piping the output of grep into another script:

./script1 | grep 'expr' | ./script2

However, the second script never gets any input. Again, nothing gets printed when I substitute script2 with cat and script1 with ping:

ping localhost | grep localhost | cat

Same thing happens if I replace grep with awk:

ping localhost|awk '{print $1}'|cat

What is going on?

user3469976
  • 233
  • 1
  • 3
  • 7

1 Answers1

10

grep is buffering (because it determines that its output isn’t a terminal; strictly speaking, this is the C library’s behaviour).

To disable this, run it with unbuffer -p (the -p is necessary for unbuffer to read from its standard input):

ping localhost | unbuffer -p grep localhost | cat

or tell grep to buffer by line (if it supports this):

ping localhost | grep --line-buffered localhost | cat
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164