Search code examples
loggingkerneloutputmonitoringbandwidth

Save only last line of a continuous standard output to a file


I'm using bmon to monitor the speed of my wireless interface. The terminal command prints to the standard output the current speed (Rx and Tx).

When I do this command...

bmon -p wlp2s0 -o ascii | tee networktraffic.txt

...the output will be printed to a txt file, like so:

Interfaces                               RX bps         pps      %    TX bps         pps      %
  wlp2s0                                      0           0                0           0       
Interfaces                               RX bps         pps      %    TX bps         pps      %
  wlp2s0                                      0           0               81B          0       
Interfaces                               RX bps         pps      %    TX bps         pps      %
  wlp2s0                                      0           0               20B          0       
Interfaces                               RX bps         pps      %    TX bps         pps      %
  wlp2s0                                      0           0                5B          0       
(...)     

I am overwriting the file and thus, as the output in the terminal is growing, so is the size of the file.

The thing is, I only want to save in the file the last line of the output (the most recent measure of speed). However, when I use the following command:

bmon -p wlp2s0 -o ascii | tail -1 > networktraffic.txt

nothing is written to the file.

I think it is also important to state that bmon prints continuously to the terminal with a 1s interval, using this command: bmon -p wlp2s0 -o ascii

I would also appreciate suggestions of other monitoring tools that would allow me to save one value of speed at a time.


Solution

  • IIUC you want the last line of the input at any given moment.

    tail -1 won't write anything to the file until it encounters end of input, which is never going to happen.

    What you need is something that writes every input line at the beginning of the file. Something like

    bmon -p wlp2s0 -o ascii | while read LINE; do echo "$LINE" > networktraffic.txt; done
    

    If you need more than one line then it's a bit more complicated, but still doable with the shell's while and read.