Piping ping through awk and redirecting output to a file

Viewed 191

My idea is to constantly ping an address, extract some information, and write that to a file.

This is what I've tried:

$ ping google.com | awk -F' ' '{ time = split($8, arr, "time="); print arr[2] }' > file.log

Then wait a couple of seconds and do:

$ file file.log
file.log: empty

However, this works as expected (prints time= for each line in the ping output):

$ ping google.com | awk -F' ' '{ time = split($8, arr, "time="); print arr[2] }'

This works too:

$ echo "64 bytes from some.net (x.x.x.x): icmp_seq=7 ttl=115 time=16.7 ms" | awk -F' ' '{ time = split($8, arr, "time="); print arr[2] }' > file.log
$ cat file.log
16.7

And this works:

$ ping -c 1 google.com | awk -F' ' '{ time = split($8, arr, "time="); print arr[2] }' > file.log

It is only when I keep ping going that it does not work. My file.log remains empty.

How can I achieve that ping constantly runs and fills my file.log?

1 Answers

Output to stdout is usually buffered - nothing is written until the buffer is full. Output to stderr is usually written immediately.

You could try:

ping google.com |\
awk 'sub("time=","",$8) { print $8 >"/dev/stderr" }' 2>file.log

or:

ping google.com |\
awk ' sub("time=","",$8) { print $8; fflush() }' >file.log
Related