0

cron job file:

46 13 * * * root /home/tmp/test_mysql.sh

script:

execute_query(){
    query="$1"
     res=`mysql --skip-column-names -e "$query"`
    echo "$res"
}

res=`execute_query "show databases"`
echo $res

error I got from when cron job executes the script successfully:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I can execute the script successfully from command line as root because the login credential for mysql are saved in /root/.my.cnf what's wrong? is cronjob somehow not reading /root/.my.cnf?

  • This link contains an example of how your my.cnf file should look like. – Leye Odumuyiwa Oct 13 '16 at 2:05
1

You should not rely on MySQL client to pick up the appropriate MySQL configuration file because of the cascading nature of how the client is reading those files. Instead you should put both your my.cnf and test_mysql.sh inside /home/tmp and use --defaults-extra-file [link] parameter in your script.

Do take note, the --defaults-extra-file needs to be the first argument of your mysql command otherwise it won't work.

execute_query(){
    query="$1"
     res=`mysql --defaults-extra-file=/home/tmp/my.cnf --skip-column-names -e "$query"`
    echo "$res"
}

res=`execute_query "show databases"`
echo $res

/root is not a very good place to put stuff in (permissions etc.) and should be avoided.

Running scripts that interact with a MySQL server should also be performed with a non-privileged user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.