Need help with shell script - output of top command

I have written shell script to send file as an attachemt of email and output of "top -o res" command as email body. it works fine if i execute manually from prompt but it does not send "top -o res" command output in email body when it is executed via crontab. Any suggestions. My script is below:
---------------

#!/usr/bin/ksh -x
 
FILE="/export/local/user/myfolder"
#### null topcommand.log file ####
cat /dev/null > topcommand.log

top -o res >> topcommand.log
generate_email() {
/usr/lib/sendmail -t <<EOF
To: my@testemail.com
From: `$hostname`
Subject: ALERT : Test Subnect Line
EMAILMESSAGE: `cat topcommand.log`
`uuencode ${FILE}/testfile.out testfile.out`
EOF
}
generate_email

------------------

Thanks

---------- Post updated at 12:41 PM ---------- Previous update was at 12:10 PM ----------

Anyone? I would be surprised if no one has done this before? I am sure there are experts who can help me to fix my script.

Thanks in advance for any help.

Hmm. I though top had an option to show something and quit immediately.

Couldn't find it on my top, so, try:

echo q | top -o res > topcommand.log

I don't know much about your generate_email() function, because I never use sendmail this way...

Thanks for your response.

Command suggested by you will work too. But my problem is when i execute script, it does put output in email body - not when it is executed via crontab.

What is difference when it is executed via crontab and manually?

Thanks

Oh, sorry. I missed that "little" detail, when i read your question!

Search the forum for Doesn't work with cron (linked is an example)

And there's a great readme here

1 Like

Perfect. It works. Thanks for your help.

There are several problems , but the error messages and the shell trace should be in unix mail for the user who owns the cron.

1) The top program expects a terminal and fails when run from cron if $TERM is not set.
Set $TERM in the script to something suitable.
When it is working, the output from "top" will include screen control characters and may need some work to make it readable.
I too don't have the commands to "top" which you are using. Most versions of "top" have a switch to make top only do one iteration then exit.

2) The file "topcommand.log" will be created in the default root directory for cron. Specify the full hierarchial directory name when referring to a file in a cron or issue a "cd" to the appropriate directory.

3) The file "testfile.out" is not written during this script. Though it has a full path name (which is good), does it exist?

4) The "-x" switch to ksh means that the shell trace will appear in unix mail for the user owning the cron. This might be useful for testing, but is unsuitable for a production script.

5) You may need to use "ux2dos" to convert the file format before "uuencode".