Search code examples
linuxbashcron

Script fails to run properly in cron.daily but works fine if I run it myself in the terminal


I have a simple script to backup my Django database. I put it in /etc/cron.daily to run everyday. Here is the simple code:

#! /bin/bash

cd /home/username
mv backups old_backups
cd myproject
source env/bin/activate
python3 manage.py dbbackup
python3 manage.py mediabackup
rm -r ../old_backups

Running the script on my own works fine. Each day when I check to see the backups folder, it's gone along with the old_backups folder. Re-running the script manually will create the backups folder and back up my database properly.

Does anyone know what could be causing this script to "sort of" run in cron.daily when it works perfectly when run in a terminal?


Solution

  • This was caused by two issues. The first is that cron jobs are run by root by default. Normally that would be okay, but the proper python packages are not installed in my virtualenv due to pip defaulting to system-wide installations for some reason. I never felt like figuring out what was wrong there and just went with it.

    I fixed this issue by running the python commands as my normal user instead of root:

    sudo -u username python3 manage.py dbbackup
    sudo -u username python3 manage.py mediabackup
    

    I have implemented this fix and ran the script as root with success. I will now wait until it successfully runs as a cron job before marking this answer as accepted.