Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percentage free swap space with `free` and `awk`

I'm trying to calculate the percentage of free swap space available. Using something like this:

free | grep 'Swap' | awk '{t = $2; f = $4; print ($f/$t)}'

but awk is throwing:

awk: program limit exceeded: maximum number of fields size=32767

And I don't really understand why, my program is quite simple, is it possible I'm having a weird range error?

like image 794
Lee Hambley Avatar asked May 29 '26 10:05

Lee Hambley


2 Answers

Try this one :

free | grep 'Swap' | awk '{t = $2; f = $4; print (f/t)}'

In your code you are trying to print $f and $t which is respectively $FreeMemory and $TotalMemory. So i guess you have about 4gig ram in total which would refer to ~ $400000 which is a little bit over the total of fields awk uses in standard config. Apart from the easier attempt with meminfo try just printing f/t which refers to the variables and you get your answer.

like image 119
Ancaron Avatar answered May 31 '26 06:05

Ancaron


Note that it might be easier/more robust to read the info by using /proc/meminfo's SwapFree line.

Something like:

$ grep SwapFree /proc/meminfo | awk '{print $2}'
like image 44
houbysoft Avatar answered May 31 '26 06:05

houbysoft