2

I am using the top command in Mac OS from this answer to grab memory usage:

$ top -l 1 -s 0 | grep PhysMem

PhysMem: 5490M used (2569M wired), 11G unused.

Can I go from that to possibly printing out "Used / Total"?

Like so:

PhysMem: 5.49G / 16.0G  

or just:

5.49G / 16.0G

Side questions:

Would that final top command be suitable to run in a few second interval and the output used for something later? Or is this not the best or most efficient command for grabbing this info and I should use something else?

I am basically trying to replicate what Luke Smith did in his video, but in Mac OS for fun, and so I can try to learn this stuff.

1

Going off of @TheMadsen's answer above, you can setup a bash script like so:

#!/bin/bash
while true; do
    top -l 1 -s 0 | grep PhysMem | awk 'BEGIN {S["G"]=1024; S["M"]=1} 
     /PhysMem:/ {U=substr($2, 1, length($2)-1) * S[substr($2, length($2))];
                 N=substr($6, 1, length($6)-1) * S[substr($6, length($6))];
                 printf("%.2fG / %.2fG\n", U/1024, (N+U) / 1024)}'
sleep 1
done

If you run this script it will periodically run the command in the background (changing the new line parameter in the printf statement from \n to \r updates it on the same line).

Otherwise you can set up a cron job to run the command periodically


  • This was exactly what I needed and works great for me. Do happen to know the impact of running a script like this on a 1 second or so interval? Probably a negligible hit to the cpu / memory and what not right? Or no? – Bloumbs Jun 11 at 9:25
2

A bit verbose, but the following awk snippet does this

$ echo 'PhysMem: 5490M used (2569M wired), 11G unused.' \
  | awk 'BEGIN {S["G"]=1024; S["M"]=1} 
         /PhysMem:/ {U=substr($2, 1, length($2)-1) * S[substr($2, length($2))];
                     N=substr($6, 1, length($6)-1) * S[substr($6, length($6))];
                     printf("%.2fG / %.2fG\n", U/1024, (N+U) / 1024)}'

5.36G / 16.36G

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .