Ubuntu – One line script to check and react to memory usage

bashshellUbuntu

I'd like to have one line of shell/bash that does something along these lines:

test "`free | grep | awk | whatever` -gt 80" && any_command

Where the total percentage of ram being used by the whole system is compared against a hardcoded number (80 in my case). test doesn't matter as long as any_command executes if ram is higher than given percentage.

  • exact bytes/megabytes instead of percentages is ok
  • this should work on typical ubuntu 14.04
  • intended for usage as a cron job
  • bonus: one-liner which does the same thing, but checks ram for a specific process

Update

There are answers on how this is a problem that the likes of monit/bluepill/god are built to solve. I agree 100%, and you should most likely follow advice in those answers. However, this question is specifically about the exact line I described, for whatever reasons that might be, assuming all the caveats and problems this might involve.

Best Answer

How about:

[ $(free -m| grep  Mem | awk '{ print int($3/$2*100) }') -gt "80" ] && echo "greater " || echo "lesser"

And for the process consumption, here is a possible part of a solution:

for p in $(pgrep bash); do total=$(($total + $(awk '/VmSize/ { print $2 }' /proc/$p/status))); done ; echo "Total memory usage: $total kb" ; unset total

Combining both of them is left as an exercise to the reader.