3

I have a script that runs fine if I invoke it from the command line, using Bash. But when cron tries to run it, it fails with a "mysql: command not found" error.

I think this is because cron is not using bash as it's shell, but I can't figure out how to make cron use bash.

I tried adding this to the top of the script:

#!/bin/bash

But no joy. How do I force cron to use bash as it's shell? I'm kind of new to bash and cron, so I may be missing something simple. I read several serverfault posts (would link to them all, but I can't, new user) and tried to understand and apply the info as best I could, plus googled a ton, but am stuck.

2 Answers2

3

it's best to use absolute paths to commands in cron scripts. so that you do not rely on any PATH settings that you may have customised.

rytis
  • 2,324
  • 1
  • 18
  • 13
  • sorry for being such a noob, but what do you mean exactly? am I using a relative path to the bash shell? or do i need to prefix the "mysql" command with something? – Jared Henderson Jan 27 '10 at 15:09
2

Pulegium is right, it isn't the type of shell thats the problem it is the PATH. When cron runs it has a very limited search path, instead of putting mysql in your command you should put /path/to/mysql with the actual path to the executable. Usually something like /usr/local/bin/mysql. You'll have to search for it to find the exact path. Also, if it was a shell issue, in your cron file you could run bash and then run your script: /bin/bash /path/to/script.sh, this would ensure that bash was the one processing the file.

einstiien
  • 2,538
  • 18
  • 18
  • excellent, thanks. pulegium was right, and your detailed explanation allowed me to actually get it working. – Jared Henderson Jan 27 '10 at 15:39
  • You may want to make the command paths variables (MYSQL=/usr/bin/mysql and then run ${MYSQL} in the script). This makes maintenance easier if/when paths change. Note that you can also set PATH environment variable in your crontab file, but absolute paths are usually better. – voretaq7 Jan 27 '10 at 17:43
  • I agree absolute paths are definitely better, you can however do source ~user/.bashrc && run_script in your cron command setting up the environment of the user you are running the script as. So it would be something like: 5 * * * * user source ~user/.bashrc && ~user/mysql_script Or some variant along those lines. It really depends on what you are trying to do. Again absolute paths are the best option but sometimes you are setting up more than just the PATH in your environment and that grows large. – ScottZ Jan 28 '10 at 03:43