I’m writing a perl script and I would really like to get the amount of cached memory currently being used on my linux box. When you run “free -m“, you get this output:
total used free shared buffers cached
Mem: 496 322 173 0 33 106
-/+ buffers/cache: 183 312
Swap: 1023 25 998
The number under “cached” is the value I want. I’ve been using Linux::SysInfo,which helps me get a lot of useful information about my box, but seems to be lacking cached memory. Does anyone know of another module or elegant way in perl to get the amount of cached memory on my machine? I know that I could get it by running this:
my $val = `free -m`;
And then running regex on val, but I’d prefer another solution if one exists. Thanks!
I am not sure if you only want a Perl solution, or if any command line solution will be acceptable. Just in case, here is a simple AWK solution:
that will print the number you are interested in.
You could assign it to some shell variable if that was necessary:
will display the value to verify.
Explanation of
awkcommand:/^Mem:/searches for a line that contains the stringMem:at the start. If it is found it prints the last item on that line which is the number we are interested in. In awk the line is split into fields based on white space.$0is the whole line,$1the first field,$2the second etc. The number of fields per line is given by the pre-defined awkNFvariable, so we can access the last field on the line with$NF.We could have also used this awk command:
which makes use of the pre-defined awk
NRvariable that contains the current line number. In this case we print the last item (field) on the 2nd line.