简体   繁体   中英

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%

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM