Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep, tee, and sleep not playing nice together

Tags:

grep

bash

tee

(echo foo && sleep 1 && echo bar) | grep -P . | tee /dev/null

The above code is the smallest case of my problem I could come up with. The expected behavior is that foo would be echo'd, a second would pass, then bar would be echo'd.

What actually happens is that a second passes then foo and bar are echo'd at the same time. If you remove either the grep or the tee command (or both, obviously) the correct behavior happens. But with them together it does not.

I assume this is some kind of buffering issue, but I don't know how to get around it. The actual script this is taking place in for me is running for quite a while and I'm not seeing any log messages till the very end. Halp! :(

like image 843
Mediocre Gopher Avatar asked Oct 22 '25 06:10

Mediocre Gopher


1 Answers

Etan's comment prompted me to look through grep's man page and I found the --line-buffered flag. Adding that fixed the problem

(echo foo && sleep 1 && echo bar) | grep --line-buffered -P . | tee /dev/null
like image 51
Mediocre Gopher Avatar answered Oct 23 '25 20:10

Mediocre Gopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!