3

I want to insert vmstat output to a file in every 10 seconds. I use the following command to do it.

vmstat 10 > vmstatfile.txt

This will create a file named vmstatfile.txt and appends to it, on every 10 seconds. What I want is, my file should always contain a single vmstat entry, the latest one, so that the file will not grow. Is this possible? Then how can I do this?

3

Well, without an argument vmstat prints a single report, so you could run it in a simple shell loop with a delay:

while true; do 
    vmstat > vmstatfile.txt
    sleep 10
done

However, that first report is the average since boot, so if you want the file to contain a report for the most recent period, you'd have to ask for at least two reports. If you want to get rid of the first report printed on each run, you can remove it (delete the third line) with sed. We'll have to use a temporary file here, so the actual target file will not contain partial output at any point.

while true; do 
    vmstat 10 2 | sed -e 3d > vmstatfile.tmp
    mv vmstatfile.tmp vmstatfile.txt
done
| improve this answer | |
0

Here is the simplest way to do it, with only a single external command running forever (vmstat) and no extra commands instead of three external commands launched every ten seconds with ilkkachu's suggestion:

vmstat 10 | while read line; do
    echo "$line" > vmstat.out
done

During the first ten seconds, the vmstat.out file will contain the average values since last reboot. Afterwards, up to date statistics will be there which is exactly what was asked for:

my file should always contain a single vmstat entry, the latest one, so that the file will not grow.

| improve this answer | |
  • like @ilkkachu mentioned in the previous post, this will print the report of average since boot, not the recent one, right? – Alfred Mar 18 '17 at 22:29
  • Not right! Answer updated to exhibit the differences between ilkkachu's answer and mine. – jlliagre Mar 20 '17 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.