LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Script runs from shell -but not from crontab (http://www.linuxquestions.org/questions/programming-9/script-runs-from-shell-but-not-from-crontab-4175418146/)

rch 07-22-2012 07:58 PM

Script runs from shell -but not from crontab
 
I wrote a script that loads data from Mysql to Monetdb. It runs perfectly when I run the script from the shell but for some reason, it does not run from crontab. I have determined that the error comes from mysql binary (as if I redirect stderr when called from crontab, I get user([username]):user([username]): as error). I am thinking that I am missing defining some environmental variables.

Any help will be greatly appreciated.

Code:

#!/bin/bash
PATH=/bin:/usr/bin:/usr/sbin/:/usr/local/bin
SCRIPTWD=<SCRIPT DIR>
USER=<USER>
MYSQL_HOST=<HOST>
topt="-n +2"
password=<PASSWORD>
cat $SCRIPTWD/tables| (while read p;
do
mysql -h<HOST> -P3306 -u$USER -p$password -B -e "select * from $p;" <db_name> | sed "s/\"/\"\"/g;s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g;s/\"NULL\"//g;s/<9d>//g"|iconv -f latin1 -t utf-8//ignore  > "$SCRIPTWD/$p.csv"
tail $topt "$p"".csv">"$SCRIPTWD/$p""_new.csv"
rm "$SCRIPTWD/$p"".csv"
mclient -d<db_name> -s "delete from $p;"
mclient -d<db_name> -E utf8 -s "COPY INTO $p from '$SCRIPTWD/""$p""_new.csv' USING DELIMITERS ',','\n','\"' NULL AS ''"
rm "$SCRIPTWD/$p""_new.csv"
done)


wpeckham 07-22-2012 08:47 PM

Cron
 
Cron executes the posix version of a shell (/bin/sh) with the default environment. There is no logon environment, so USER is not defined, PATH may differ, and other factors. A careful study of the ENVIRONMENT section and start-up sections of the shell man page should give you a clue as to what is going on.

In short, define the needed environment variables in the script itself to ensure that the values and calls are as you need them.

rch 07-22-2012 09:00 PM

Thank wpckeham, I know that USER is not defined- that's why I define USER (even though I don't think it is required for mysql client to run). I don't think that is the problem though. Do you know which environment variable am I missing here?

NevemTeve 07-23-2012 12:53 AM

try to debug

Code:

set -x
exec >/tmp/debug.$$ 2>&1


wpeckham 07-23-2012 01:37 PM

Troubleshooting
 
Second that (set -x is your friend)
Make sure to check the expanded mysql line in that log, and make certain that the expansions and substitutions are as you expect.

rch 07-24-2012 05:07 PM

Thanks very much NevemTeve and wpeckham, the issue was not mysql (my bad), it was the location of the directory where the script is being run. The directory also has a .monetdb file which supplies the username and password for the Monetdb database (AFAIK, mclient does not have a password parameter). That was what was breaking it- and your suggestion helped me find the problem.


All times are GMT -5. The time now is 08:21 AM.