zOthix
zOthix

Reputation: 556

How to get overall RAM usage (e.g. 57%) on Linux

I am wondering how you can get the system RAM usage and present it in percent using bash, for example.

Sample output:

57%

Upvotes: 0

Views: 2999

Answers (1)

blurfus
blurfus

Reputation: 14031

If you are looking for a bash script, I just came up with this.

There may be more efficient ways of doing it but I believe this is what you are looking for:

#!/bin/bash

# grab the second line of the ouput produced by the command: free -g (displays output in Gb)
secondLine=$(free -g | sed -n '2p')

#split the string in secondLine into an array
read -ra ADDR <<< "$secondLine"

#get the total RAM from array
totalRam="${ADDR[1]}"

#get the used RAM from array
usedRam="${ADDR[2]}"

# calculate and display the percentage
pct="$(($usedRam*100/$totalRam))"
echo "$pct%"

if you save this into a file (call it pct.sh), then you can run it by

$./pct.sh
33%

Note bash does not support floats, only integers (IIRC) so the precision of the calculation is rounded.

If you need more precision, you might need to use a different shell that supports floats, like zsh

Credit where credit is due: created with help from: 1 2 3

Upvotes: 4

Related Questions