2

I'm writing small geeklet for geektool, to alert me when sum of inactive and free RAM on my Mac will become slow. I'm not really good with bash, so I have a problem with final output (getting blank). Here is code:

inMem=$(top -l 1|awk '/PhysMem/ {print $6}'|sed s/M//) | freeMem=$(top -l 1|awk '/PhysMem/ {print $10}'|sed s/M//) | totalMem=$inMem+$freeMem | bc | echo $totalMem

Also wonder if my issue is optimal or not. Thanks a lot.

chepner
  • 497,756
  • 71
  • 530
  • 681

3 Answers3

2

I wonder if this could actually simplify your commands. I can't test it since I'm not on OSX but I hope it works.

read inMem freeMem totalMem < <(top -l 1 | awk '/PhysMem/ { i = $6; sub(/M/, "", i); f = $10; sub(/M/, "", f); printf("%d %d %d\n", i, f, i + f); exit; }')
echo "inMem: $inMem"
echo "freeMem: $freeMem"
echo "totalMem: $totalMem"
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • +1 for the general approach, although it could still be simplified a lot if you don't need to have the values in shell variables. – tripleee Sep 04 '13 at 15:49
  • @tripleee My initial version of it was actually only the command itself without showing the value for `inMem` and `freeMem` but I can't generalize what the OP really wants. – konsolebox Sep 04 '13 at 17:01
  • 1
    Oh I mean simply `top -l 1 | awk '... END { print "inMem: " i; print "freeMem: " f; print "totalMem: " i+f }'` – tripleee Sep 04 '13 at 18:45
  • 1
    Thanks a lot) echo commands just for testing, I need only totalMem value, due its show total memory which can be used. – Wiedzmin478 Sep 06 '13 at 15:53
-1

Instead of parsing top, use the /proc/meminfo file. For example, with:

$ head -2 /proc/meminfo
MemTotal:        4061696 kB
MemFree:          335064 kB

you can see to total and free memory

user000001
  • 32,226
  • 12
  • 81
  • 108
-1

user000001 answer is right, but then the question is "How to get /proc/meminfo output into variables?"

You can use this pure bash solution for parsing:

read -d '' _  memTotal _ _ memFree _ < <(head -2 /proc/meminfo)
Community
  • 1
  • 1
Aleks-Daniel Jakimenko-A.
  • 10,335
  • 3
  • 41
  • 39