I'm hoping to be able to collect system CPU information using sar and want to have one file where it contains all the data collected and a second file which only stores the last entry.
Output below would be my measurements.txt file
14:54:45 CPU %user %nice %system %iowait %steal %idle
14:54:48 all 6.12 0.00 35.03 2.72 0.00 56.12
14:54:51 all 6.23 0.00 34.60 0.00 0.00 59.17
14:54:54 all 9.69 0.00 47.75 0.35 0.00 42.21
14:54:57 all 5.23 0.00 31.71 1.39 0.00 61.67
14:55:00 all 7.14 0.36 33.21 0.00 0.00 59.29
14:55:03 all 6.23 0.00 32.53 1.04 0.00 60.21
14:55:06 all 7.89 0.00 30.82 0.00 0.00 61.29
14:55:09 all 8.51 0.00 31.91 3.55 0.00 56.03
The last entry starting at 14:55:09 would be the only entry in my last_entry.txt file.
However any time I've tried to do this, I've been unable to get the last entry from the sar command in my last_entry.txt file. I've been able to send the sar output to measurements.txt file as shown in the example, however it's the last part I'm really struggling with.
At one stage, I managed to get one output to the last_entry.txt file however it wasn't the last entry, so I'm guessing that perhaps that part of my script only gets carried out once. Problem is, I don't know how to get it to continuously get the last entry until I cancel it.
Here's my code for the script which sends the output of sar to a text file and then sends the first entry instead of the last entry to the second file.
sar -u 3 > measurements.txt & tail -1 measurements.txt > last_measurement.txt
The problem is with the &
command separator. It causes the sar
command to run in the background while you fetch the current last line of its output file at some indeterminate time during its execution. You want sar
to finish, then run tail
.
sar -u 3 > measurements.txt ; tail -1 measurements.txt > last_measurement.txt
or more idiomatically just
sar -u 3 > measurements.txt
tail -1 measurements.txt > last_measurement.txt
or with tee
to keep it all in one pipeline
sar -u 3 | tee measurements.txt | tail -n 1 >last_measurement.txt