Human readable system memory reading from CLI?

31,454

Solution 1

If that's all you need, just use free:

$ free -h | gawk  '/Mem:/{print $2}'
7.8G

free returns memory info, the -h switch tells it to print in human readable format.

Solution 2

On Linux,

read x memtotal x < /proc/meminfo

Would store the total mem amount in $memory in number of kiB. That's the amount of memory available to Linux, the same as reported by free.

If you want the installed RAM, you could do things like:

awk '{s+=$0};END{print s}' /sys/bus/mc*/devices/dimm*/size

To get the size in MiBs. Or

awk '{s+=$0};END{printf "%.2gG\n", s/1024}' /sys/bus/mc*/devices/dimm*/size

If you want the size in GiB.

Share:
31,454

Related videos on Youtube

JohnyMoraes
Author by

JohnyMoraes

Updated on September 18, 2022

Comments

  • JohnyMoraes
    JohnyMoraes almost 2 years

    On OS X, I get a nice human readable system memory reading like so:

    printf -v system_memory \
              "$(system_profiler SPHardwareDataType \
                 | awk -F ': ' '/^ +Memory: /{print $2}')"
    echo "$system_memory"
    

    prints out the friendly:

    4 GB
    

    Although this on Linux is correct:

    lshw -class memory
    

    it outputs:

    size: 4096MiB
    

    I need to painfully parse it and try to make it into a string as nice as the one above.

    Am I using the wrong command?

    • Admin
      Admin about 11 years
      "I need to painfully parse it"... That big ugly thing for osx isn't painful? :-)
    • Admin
      Admin about 11 years
      @Patrick: I dislike OS X when comparing it to Linux!
  • JohnyMoraes
    JohnyMoraes about 11 years
    I did not know free had a (nice) -h switch. Thanks. Very interesting how free deems 4.0G (which is what I get) more human friendly than 4 GB. "Mum, I'm hungry, I'd like 1.0 apple, please." If this is the best we have on Linux, I should probably just parse the number out and replace G with GB myself.. Very rarely do we see HDDs, for example, advertised as "320G" rather than "320 GB". :(
  • Stéphane Chazelas
    Stéphane Chazelas about 11 years
    @Robottinosino, HDD sizes are expressed in GB (10^9 bytes), while memory is generally expressed in GiB (2^30 bytes), 4.0G gives you an idea of the precision. With 4GB, you don't know if it's exactly 4GB (or 4GiB?) or 4.4GB rounded down to 4 or 3.6G rounded up to 4.
  • countermode
    countermode over 7 years
    You need to parse that as well.
  • aalaap
    aalaap about 7 years
    @Robottinosino If you want to round it off to a more human-readable number and add GB, try free -h | gawk '/Mem:/{print $2}' | rev | cut -c 2- | rev | xargs printf "%.*fGB\n" 0