Search code examples
croncron-task

Crontab CD to Directory


All of my cronjob scripts run from a specific directory. Can I add cd /FOLDER/PATH at the top of the crontab file and expect all scripts to be run from that directory?

Currently all my crontab functions are like this (ignore lack of specific run frequencies)

* * * * * cd /FOLDER/PATH && python3 File.py
* * * * * cd /FOLDER/PATH && python3 File2.py
* * * * * cd /FOLDER/PATH && python3 File3.py

I would rather it be like

cd /FOLDER/PATH
* * * * * python3 File.py
* * * * * python3 File2.py
* * * * * python3 File3.py

Solution

  • since crontab file is not actually what is running when a task is being triggered what you will to do would not work since cron tasks are run from the cron daemon. A solution to beautify the commands a bit would be to add the path were the actual scripts are to the PATH env variable on the crontab file

    PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/path/to/scripts
    

    and then do something like this:

    * * * * * /FOLDER/PATH/File.py
    * * * * * /FOLDER/PATH/File2.py
    * * * * * /FOLDER/PATH/File3.py
    

    Note that name.py files should have the interpreter defined at the top of the file for it to work.