3

I have a script which dumps out database and uploads the SQL file to Swift. I've run into the issue where the script runs fine in terminal but fails in cron.

A bit of debugging and I found that the /usr/local/bin/swift command is not found in the script.

Here's my crontab entry:

*/2 * * * * . /etc/profile; bash /var/lib/postgresql/scripts/backup  

Here's what I've tried:

  1. Using full path to swift as /usr/local/bin/swift
  2. Executing the /etc/profile script before executing the bash script.

How do I solve this?

  • what is the reason of failure in cron? – Luv33preet Aug 8 '17 at 12:01
  • @Luv33preet I have logged which swift and that returns empty. Beyond that, $? returns 1. Am I missing something? – Little Child Aug 8 '17 at 12:02
  • if your script requires root permissions, better add the cronjob in /etc/crontab. – Luv33preet Aug 8 '17 at 12:03
  • @Luv33preet would it cause any issues? the script needs to be run under postgres user. – Little Child Aug 8 '17 at 12:04
  • check this if it helps, askubuntu.com/questions/907421/cronjob-different-behaviours – Luv33preet Aug 8 '17 at 12:04
5

Cron doesn't run with the same environment as a user. If you do the following you will see what I mean:

type env from your terminal prompt and make note of the output.

Then set a cron job like this and compare it's output to the previous:

*/5 * * * * env > ~/output.txt 

You will find that the issue is likely because crontab does not have the same PATH variable as your user. As a solution to this you can (from your postgres user) echo $PATH and then copy the results of that to the first line of your crontab (something like this)

PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/jbutryn/.local/bin:/home/jbutryn/bin

Or if you want to be more specific you can simply add the following:

PATH=$PATH:/usr/local/bin

However I normally always put my user's PATH in crontab because I haven't yet heard a good reason not to do so and you will likely run into this issue again if you don't.

0

You made one of the most common cron mistakes. If you using specific environment add path to $PATH:

# User specific environment and startup programs
PATH=$PATH:$HOME/bin:/usr/sbin:/usr/bin:/script
export PATH

Also check your cron log (/var/log/cron or /var/log/syslog). And check user's permission for binary files.

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.