How to get the total physical memory in Bash to assign it to a variable?
BashBash Problem Overview
How can I get the total physical memory in bytes of my Linux PC?
I need to assign it to a bash script variable.
Bash Solutions
Solution 1 - Bash
grep MemTotal /proc/meminfo | awk '{print $2}'
The returned number is in KB
Solution 2 - Bash
phymem=$(awk -F":" '$1~/MemTotal/{print $2}' /proc/meminfo )
or using free
phymem=$(LANG=C free|awk '/^Mem:/{print $2}')
or using shell
#!/bin/bash
while IFS=":" read -r a b
do
case "$a" in
MemTotal*) phymem="$b"
esac
done <"/proc/meminfo"
echo $phymem
Solution 3 - Bash
I came up with this one under the assumption, that the physical memory will be the first number in free's output:
free -m | grep -oP '\d+' | head -n 1
This allows you to configure free to output the unit you want (-m, -g, ...) and it is independent of the system language (other answers depend on the "Mem:" string in free's output which may change based on the language).
Solution 4 - Bash
How about
var=$(free | awk '/^Mem:/{print $2}')
Solution 5 - Bash
> I'll try to make this answer self explanatory, just keep up with me.
To get the description of memory, you can use the free
utility :
free -t
Output (in KB):
total used free shared buff/cache available
Mem: 8035900 3785568 324984 643936 3925348 3301908
Swap: 3906556 271872 3634684
Total: 11942456 4057440 3959668
To extract all of these values from this output in a single column :
free -t | grep -oP '\d+'
Output (in KB):
8035900
3866244
266928
650348
3902728
3214792
3906556
292608
3613948
11942456
4158852
3880876
> Note : Minute difference can be there in values, which doesn't matter most of the times.
If you just want to get the total
physical memory (mem+swap), it is the 10th value in above output :
free -t | grep -oP '\d+' | sed '10!d'
Output (on my PC):
11942456
> Note: All the above outputs are in Kilo Bytes
. If you want in Mega Bytes
or Giga Bytes
just append -m
or -g
after -t
in
> above free
commands respectively.
>
> For Example :
>
> free -t -g | grep -oP '\d+' | sed '10!d'
>
> Output (in Giga Bytes on my PC) :
>
> 11
Solution 6 - Bash
Silly inline python version, which looks overly complicated, but is actually kind of useful.
freemem=$(echo -e 'import re\nmatched=re.search(r"^MemTotal:\s+(\d+)",open("/proc/meminfo").read())\nprint(int(matched.groups()[0])/(1024.**2))' | python)
It returns the memory in GB.