Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script with lsof works well on shell not on cron

I have a small script do count open files on Linux an save results into a flat file. I intend to run it on Cron every minute to gather results later. Script follows:

/bin/echo "Timestamp: ` date +"%m-%d-%y %T"` Files: `lsof | grep app | wc -l`"

And the crontab is this:

*/1 * * * * /usr/local/monitor/appmon.sh >> /usr/local/monitor/app_stat.txt

If I run from shell ./script.sh it works well and outputs as:

Timestamp: 01-31-13 09:33:59 Files: 57

But on the Cron output is:

Timestamp: 01-31-13 09:33:59 Files: 0

Not sure if any permissions are needed or similar. I have tried with sudo on lsof without luck as well.

Any hints?

like image 890
Neill Lima Avatar asked Jan 31 '13 14:01

Neill Lima


People also ask

What should I do to run a script on specific time without cron?

If not using cron, you will have to arrange for the script to re-execute itself at a particular time in the future, maybe using at (which is part of cron), or by sleeping (which would make the executions drift over time), and you would additionally have to set up an initial execution of the script at reboots (again, ...

Does cron run in a shell?

Cron is a system that helps Linux users to schedule any task. However, a cron job is any defined task to run in a given time period. It can be a shell script or a simple bash command. Cron job helps us automate our routine tasks, it can be hourly, daily, monthly, etc.


1 Answers

from your working cmd-line, do

which lsof
which grep
which wc
which date

Take the full paths for each of these commands and add them into your shell script, producing something like

/bin/echo "Timestamp: `/bin/date +"%m-%d-%y %T"` Files: `/usr/sbin/lsof | /bin/grep app | /bin/wc -l`"

OR you can set a PATH var to include the missing values in your script, i.e.

 PATH=/usr/sbin:${PATH}

Also unless you expect your script to be run from a true Bourne Shell environment, join the early 90's and use the form $( cmd ... ) for cmd-substitution, rather than backticks. The Ksh 93 book, published in 1995 remarks that backticks for command substitution are deprecated ;-)

IHTH

like image 72
shellter Avatar answered Sep 21 '22 00:09

shellter