jenglee
jenglee

Reputation: 353

Set a Bash Command Return as a Variable

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

Answers (4)

creaktive
creaktive

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

Jacopofar
Jacopofar

Reputation: 3507

You can use backticks on the command:

export var=`command`

Upvotes: 0

dogbane
dogbane

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

sampson-chen
sampson-chen

Reputation: 47269

I believe this is what you are looking for:

var1=$(free -m | grep "Mem: " | awk '{print ($3/$2)*100}')

Explanation:

  • The $(...) syntax is called command substitution in shell.
  • It spawns a subshell to execute whatever is inside the parentheses, then returns anything printed out to 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

Related Questions