Top Command Output is Empty when run from cron

2020-04-18 07:56发布

I was trying to redirect the TOP command output in the particular file in every 5 minutes with the below command.

top -b -n 1 > /var/tmp/TOP_USAGE.csv.$(date +"%I-%M-%p_%d-%m-%Y")

-rw-r--r--   1 root root 0 Dec  9 17:20 TOP_USAGE.csv.05-20-PM_09-12-2015
-rw-r--r--   1 root root 0 Dec  9 17:25 TOP_USAGE.csv.05-25-PM_09-12-2015
-rw-r--r--   1 root root 0 Dec  9 17:30 TOP_USAGE.csv.05-30-PM_09-12-2015
-rw-r--r--   1 root root 0 Dec  9 17:35 TOP_USAGE.csv.05-35-PM_09-12-2015

Hence i made a very small (1 line) shell script for this, so that i can run in every 5 minutes via cronjob.

Problem is when i run this script manually then i can see the output in the file, however when this script in running automatically, file is generating in every 5 minutes but there is no data (aka file is empty)

Can anyone please help me on this?


I now modified the script and still it's the same.

#!/bin/sh
PATH=$(/usr/bin/getconf PATH)

/usr/bin/top -b -n 1 > /var/tmp/TOP_USAGE.csv.$(date +"%I-%M-%p_%d-%m-%Y")

2条回答
小情绪 Triste *
2楼-- · 2020-04-18 08:05

I met the same problem as you.

Top command with -b option must be added.Saving top output to variable before we use it.

the scripts are below

date >> /tmp/mysql-mem-moniter.log

MEM=/usr/bin/top -b -n 1 -u mysql

echo "$MEM" | grep mysql >> /tmp/mysql-mem-moniter.log

查看更多
再贱就再见
3楼-- · 2020-04-18 08:15

Most likely the environment passed to your script from cron is too minimal. In particular, PATH may not be what you think it is (no profiles are read by scripts started from cron).

Place PATH=$(/usr/bin/getconf PATH) at the start of your script, then run it with

/usr/bin/env -i /path/to/script

Once that works without error, it's ready for cron.

查看更多
登录 后发表回答