1
#!/BIN/BASH
# To alert whenever lsof crosses 80%

maxlimit=32000
echo 'Max limit is ' $maxlimit
tlimit=$(bc <<< $maxlimit*0.8)
echo 'Treshold limit at 80% ' $tlimit
a=$(lsof | wc -l)
echo 'Current usage ' $a
if [ $(bc <<< "$a > $tlimit") -eq 1 ]
then
        echo 'lsof =' $a 'has exceeded 80% of maximum limit' | /usr/bin/Mail -s "ALERT!!!" "*****@cisco.com"
fi

* * * * * bash /root/vasanth/lsef/script.sh

In the above script, the output is to send a mail to the corresponding Mail ID .

When I run it manually it sends the mail.

But, when it is scheduled in cron, the mail is not being sent.

I cant understand what the problem is. How could I debug it?

peterh
  • 9,731
Vasanth
  • 11

2 Answers2

1

1. First: use #!/bin/bash instead of #!/BIN/BASH

With #!/BIN/BASH if you run script like this:

bash script.sh

..everything work fine.

But if you execute:

./script.sh

..you gets an error:

-bash: ./script.sh: /BIN/BASH: bad interpreter: No such file or directory

2. Execute this command:

echo 'PATH='$PATH

add output to the beginning of the script.

Example:

# echo 'PATH='$PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
  • Which path is it that may be undetermined? He's using an absolute path for Mail. It would be lsof, wc, or bc that would not be found, but they usually live in /usr/bin... Would be very strange if that wasn't in $PATH (though he may have mangled it somewhere). – Kusalananda Sep 08 '17 at 13:32
1

The main problem with similar cron tasks is, that you can't easily debug them.

Typically, cron tasks should work silently if there is no error, but they should be very verbose in the case of any error.

Extending EgorVasilev's answer, you can easily turn on a "debug mode" in a bash script script by the

#!/bin/bash -x
exec 2>>/var/log/cron.log

commands. The first interprets your script by the -x flag, what means, you will get all executed command in the stderr.

And exec 2>>/var/log/cron.log is a command what doesn't executes anything, rather it redirects the stdandard error into a log file, in append mode. Essentially, the shell interpreter "re-executes" itself with the given redirections, without even changing the script execution context.

peterh
  • 9,731