Bash – Using ‘ping’, ‘cut’ and ‘tee’ together

bashpipetee

So, I understand that by using 'tee' I can redirect the output of a command such as 'ping' to stdout as well as a file.

For example:

> ping google.com | tee somefile

This would display the ping statistics on terminal and write them to 'somefile'.

Now, if I wish to modify the output from 'ping', I can use 'cut' in such a way:

> ping google.com | cut -d' ' -f 1

But, if I wish to use all the three commands together, I get a no output on stdout and an empty file.

> ping google.com | cut -d' ' -f 1 | tee somefile

What am I doing wrong? Is there a better way to do this? Somehow I feel I am not using 'tee' properly. Any insight would be appreciated.

I'm using bash shell, if this is relevant.

Best Answer

Your pipe commands, as a non-terminal destination, are buffering your output. It will show up eventually, but only when quite a lot of output builds up or the ping command exits.

You can use ping -c 5 google.com to set a specific number of packets to be sent and then ping will exit. Your output comes back and the pipes should work as expected.

Edit: another workaround uses stdbuf to avoid pipe buffering and awk to avoid some internal cut buffering and lets the ping run continuously:

ping www.google.com | stdbuf --output=0 awk '{print $1}' | tee /tmp/file
Related Question