Running top from crontab
From Foochal
Problem running 'top' in crontab
I was trying to track how much memory tomcat was using and send alert email when the memory used exceeded a certain limit. So I wrote a simple cronjob.
To determine amount of memory used I used the following command:
memUsed=`top -n 1 | grep tomcat | grep java | awk '{print $6}' | perl -pe 's/M//g'`
The program runs fine from command line, however, when I run it from the crontab, it always shows the memUsed = "0"
Solution
I spent more than an hour trying to figure out why my cronjob wasn't working. Finally, I stumbled upon the following flag in top: b Batch mode. Useful for sending output from top to other programs or to a file. In this mode, top will not accept command line input. It runs until it produces the number of iterations requested with the n option or until killed. Output is plain text suitable for display on a dumb terminal.
So I added the -b flag and top works from crontab.
memUsed=`top -b -n 1 | grep tomcat | grep java | awk '{print $6}' | perl -pe 's/M//g'`

