14

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?

Neill Lima
  • 331
  • 3
  • 11

1 Answers1

20

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

shellter
  • 36,525
  • 7
  • 83
  • 90
  • Thanks Shellter, Right on target! I've set to the paths using the which command which worked well. Thanks a lot! Speaking of which do you know why I get different counters for: lsof | grep app | wc -l And: ls -l /proc/{PID}/fd/ | wc -l ? – Neill Lima Jan 31 '13 at 15:18
  • Found on: http://serverfault.com/questions/323810/whats-the-difference-between-lsof-p-pid-wc-l-and-ls-proc-pid-fd-w – Neill Lima Jan 31 '13 at 15:22
  • I'm not an expert, (I worked for years on systems that didn't have `/proc/...` ;-)), but I wouldn't expect them to return the same, as your limiting the output of `lsof` with `grep apps`, while I'm guessing that `/proc/{PID}/fd` is only the files attached to the current process. I would try `lsof | sort > lsof.out; ls -l /proc/.. | sort > procs.out; diff lsof.out procs.out` to see the raw data that is driving the counts. Good luck to all. – shellter Feb 01 '13 at 02:42