Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The following command gives memory usage into normal form.

awk '/^Mem/ {printf("%u%%", 100*$3/$2);}' <(free -m)

I want to get it in valid json form.

Desire output:

share|improve this question
up vote 2 down vote accepted

Perhaps this, read info from proc fs, and use bc to calculate:

tot=$(awk '{ if (/MemTotal:/) {print $2} }' </proc/meminfo)
free=$(awk '{ if (/MemFree:/) {print $2} }' </proc/meminfo)
pers=$(echo "scale=0; 100 - 100 * $free / $tot" | bc)
echo '{"Memory":"'$pers'"}'
share|improve this answer
Note that your formula needs minor adjustment. The question used “100 * used / total”, while you use “100 * free / total”. – manatwork Mar 26 '13 at 8:20
@manatwork right, thanks – warl0ck Mar 26 '13 at 8:36
Thank You friend – K.K Patel Mar 26 '13 at 8:58

If using awk is not mandatory, I prefer ruby for JSON formatting. Much longer that a bare awk script, but easier to extend it later:

ruby -rjson -nae 'BEGIN{j={}};j["Memory"]="#{(100*$F[2].to_f/$F[1].to_f).to_i}%"if/^Mem/;END{puts j.to_json}' <(free -m)
share|improve this answer

With an one-liner :

awk '$1=="MemTotal:"{t=$2} $1=="MemFree:"{f=$2}END{printf "{\042Memory\042:\042%s\042}\n",  int(100 - 100 * f / t)}' /proc/meminfo
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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