0

I've been scratching my head on this for a while. I have a script that is run by a root cron job. The script executes, but there is a script inside the script that wont execute. Here is what we will call scriptA

#!/bin/bash
lines=`wc -l < /var/www/log/addme`;
DATE=`date +%Y-%m-%d`

if [[ $lines > 4 ]];
then
echo " " > /var/www/log/addme
RESTART=/var/www/log/restart.sh
$RESTART
else
echo "No new hosts added" | wall
fi

Basically what the restart.sh script does is to restart a service. Everything works just fine when I run them from terminal, but not as cron jobs... I also tried to just put

./restart.sh
/var/www/log/restart.sh

But with same result. Any thoughts?

4
  • Does the cron job run as root or as some other user? Does the user have access to /var/www/log? Have you tried logging what happens when the first script tries to call the second one (change $RESTART to $RESTART >/var/tmp/foo.log 2>&1)? Commented Nov 7, 2012 at 18:00
  • What are the permissions on /var/www/log/restart.sh? Is it executable? If not, you can chmod +x it, or run it with bash $RESTART in your scriptA. Commented Nov 7, 2012 at 18:12
  • Also, set a MAILTO variable inside your crontab, so that you can see what errors are generated by the job. Commented Nov 7, 2012 at 18:13
  • Besides, the [[ $lines > 4 ]] is doing a lexical comparison, which would bring problems with $lines >= 10. You may replace the '>' with '-gt' Commented Nov 7, 2012 at 18:37

1 Answer 1

2

I suspect you're running into problems with the minimal environment that cron runs its jobs with. The biggest thing is that the PATH is very minimal, and is your script is probably using some commands that can't be found.

If this is the problem, there are several ways to fix it: the easiest is generally to add an appropriate definition of PATH to the crontab file, before the entry that runs your script. Something like this:

PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
0 * * * *       /var/www/log/scriptA

The second is to add a similar assignment at the beginning of scriptA. The third option is to go through both of the scripts, and use full paths for all of the commands you use (e.g. /usr/bin/wc instead of just wc).

BTW, there is also a problem with the test [[ $lines > 4 ]] -- inside [[ ]], > does a string (alphabetical) comparison, not a numeric comparison. This is a problem because, alphabetically, 10 is less than 4. Use either [[ $lines -gt 4 ]] or (( lines > 4 )) to get a numeric comparison.

Sign up to request clarification or add additional context in comments.

1 Comment

This solved my problem and also the problem I did not know exist. Thanks a lot! I'll remember the cron PATH's in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.