Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:
Example:

{"Memory":"80"}
share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

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

#!/bin/bash
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
add comment

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
add comment

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
add comment

Your Answer

 
discard

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.