3

Below command generates output every second for 60 seconds.

sar -n DEV  1 60 | grep lo

If I redirect it to a file, the file sar.log is updated continuously i.e. every second

sar -n DEV  1 60 > sar.log &

However, as soon as pipe it and then redirect it to a file, it populates the file sar.log only after it has finished i.e. after 60 seconds.

sar -n DEV 1 60 | grep lo > sar.log &

How do I grep and redirect to a file so that the log file is updated continuously i.e. every second

I am ok with using something other than grep if it serves my purpose of selecting something and redirecting to a file every second.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
user2250246
  • 3,807
  • 5
  • 43
  • 71

2 Answers2

6

With GNU grep: Add option --line-buffered to use line buffering on output. This can cause a performance penalty.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
2

I found that How to 'grep' a continuous stream? is also a good answer.

sar -n DEV 1 10 | stdbuf -o0 grep lo > sar.log &
user2250246
  • 3,807
  • 5
  • 43
  • 71