How to output redirect to overwrite file while command is running Linux?

5.1k views Asked by At

I am not sure if this is even possible. But I am using this command to get network throughput.

ifstat -t -S -i wlan0

Run just like that it updates inline on the console but when I pipe it, it appends a new line to the file.

ifstat -t -S -i wlan0 >> /tmp/transfer.txt

  Time          wlan0
HH:MM:SS   KB/s in  KB/s out

21:33:35      4.27    201.47
21:33:36      4.20    178.88
21:33:37      4.41    190.76
21:33:38      4.32    186.61
21:33:39      5.07    177.42
21:33:40      4.15    182.87
21:33:41      5.70    180.93
21:33:42      4.21    194.71
21:33:43      3.80    181.35
21:33:44      3.86    185.57
21:33:45      3.92    189.78
21:33:46      4.08    195.29
etc...

OK I understand using this will overwrite the file.But only after I run it the first time.Not DURING the execution of the app.

ifstat -t -S -i wlan0 >> /tmp/transfer.txt

I really do not need to keep a log of all the transfer rates and only interested in writing that one line on every update while the application is running. Instead of appending lines during executions, I want it to create a new file or overwrite it every second.

2

There are 2 answers

7
Dan Cornilescu On BEST ANSWER

Technically you're not piping, but redirecting output.

Looks like you want to use > instead of >>?

For obtaining just the last line while ifstat is executing you could extract it in a 2nd file like this:

while true; do tail -1 /tmp/transfer.txt > /tmp/transfer2.txt; sleep .5; done

To overwrite the file each time with out keeping a log.

while true; do ifstat -t -i wlan0 1 1 | tail -1 > /tmp/transfer.txt; sleep .5; done;
2
Atafar On

You can try one of the following (I do not have your version of ifstat, so I cannot verify this on my own system).

while /bin/true; do ifstat -t -i wlan0 1 > tmp/transfer.txt; sleep 1; done

or perhaps just

ifstat -t -i wlan0 > tmp/transfer.txt

So, don't use the -S flag since this does not work when redirecting to file.