2

I would like to calculate the percentage of free memory using Linux bash shell scipts.

Example:
bash-4.1$ free
              total       used       free     shared    buffers     cached
 Mem:      12223100   11172812    1050288        316     714800     629944
 -/+ buffers/cache:    9828068    2395032
 Swap:      6266872    5852824     414048

Ex. (1050288/12223100) * 100 = %free memory-I want to do this using scripts.

Thanks Puspa

1 Answer 1

5
memfree=`cat /proc/meminfo | grep MemFree | awk '{print $2}'`; 
memtotal=`cat /proc/meminfo | grep MemTotal | awk '{print $2}'`; 
bc -l <<< "$memfree * 100 / $memtotal" 

the proc/meminfo file displays everything you should need about memory.

You use grep to isolate the line about Free Memory and Total memory, and store it in variables. Then you use bc -l for the float division.

EDIT: If there is no bc installed, you may use echo :

echo $(($memfree.0 * 100 / $memtotal))
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks You.I am using bash shell in Linux.There is no bc installed.what is the alternate way ?
You can use echo then :
You invoke a total of 7 processes here (2 cat, 2 awk, 2 grep, 1 bc) when it can all be done with a single awk. Mmmm...
This might be better... awk '/MemFree/{free=$2} /MemTotal/{total=$2} END{print (free*100)/total}' /proc/meminfo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.