Search code examples
shellcroncron-task

Cron wont create directories


I have crontab entry , cannot find a problem with it, but it does not work.

*/5 * * * * mkdir -m /home/ubuntu/aus/cron/$(date +\%Y\%m\%d)/$(date +\%R) && /usr/bin/python3 /home/ubuntu/aus/test.py >> /home/ubuntu/au/cron/$(date +\%Y\%m\%d)/$(date +\%R)/cron.log 2>&1

I am trying to make cron to make directory inside cron folder and put the cron log file inside it.


Solution

  • Use this as /home/ubuntu/aus/test.sh

    #!/bin/bash
    
    rootdir=/home/ubuntu/aus
    crondir=$(date "+$rootdir/cron/%Y%m%d/%R")
    
    mkdir -p "$crondir"
    /usr/bin/python3 "$rootdir/test.py" >> "$crondir/cron.log" 2>&1
    

    And then the cron entry will be

    */5 * * * * /home/ubuntu/aus/test.sh
    

    The magic of mkdir -p is that a) it creates each missing directory in the path and b) it does not error if the directory already exists.