Reputation: 353
If we can perform this in Perl It would be fine as well. I don't know if this is even possible but this is what i want to be able to do. I am trying to get a memory percentage of memory being used (There may be better ways of doing this, please let me know)
I have this bash command
free -m | grep "Mem: " | awk '{print ($3/$2)*100}'
This will return a number, but what I want to do is set a variable to the output of the command.
So var1= Output of the above command
Upvotes: 1
Views: 558
Reputation: 5210
If you're using Linux (or any Unix with compatible /proc interface), you can get % of used memory this way:
var1=$(perl -ne '/(\w+):\s*(\d+)/ and ($mem{$1} = $2) }{ printf "%0.2f", 100 - 100 * $mem{MemFree} / $mem{MemTotal}' /proc/meminfo)
Note that is is generally a good idea to subtract buffers & cache (OS caching tends to fill all the available RAM):
var2=$(perl -MList::Util=sum -ne '/(\w+):\s*(\d+)/ and ($mem{$1} = $2) }{ printf "%0.2f", 100 - 100 * sum(@mem{qw{Buffers Cached MemFree}}) / $mem{MemTotal}' /proc/meminfo)
Upvotes: 0
Reputation: 274532
You don't need to use grep
, if you are using awk
. You can simplify your command to:
var1=$(free -m | awk '/Mem:/{print ($3/$2)*100}')
Upvotes: 4
Reputation: 47269
I believe this is what you are looking for:
var1=$(free -m | grep "Mem: " | awk '{print ($3/$2)*100}')
Explanation:
$(...)
syntax is called command substitution in shell.stdout
within that subshell.Aside:
The alternative syntax is with backticks:
var1=`free -m | grep "Mem: " | awk '{print ($3/$2)*100}')`
but it's not the preferred method due to readability and nesting issues.
Upvotes: 5