3

I have a very long (and messy) crontab (on my Mac). So I started cleaning it up by introducing variables for instance. Then I realized that concatenating variables (just like in a Bash script) does not work in my crontab. This is what I have:

SHELL=/bin/bash
HOME=/Users/leuchtturm
# [1] Previously had this, but this does not seem to work
# $HOME is not being evaluated? Why?
# 
# VIRTUALENV_PYTHON=$HOME/.virtualenvs/py361/bin/python
# Now I have this (elaborated)
VIRTUALENV_PYTHON=/Users/leuchtturm/.virtualenvs/py361/bin/python

# the crontab entry
# Here $HOME is being expanded, but not in the example above [1]
#
*/2  *  *  *  *   source $HOME/.config_vars && $VIRTUALENV_PYTHON $HOME/workspace/monitoring/check_server.py

So in this line VIRTUALENV_PYTHON=$HOME/.virtualenvs/py361/bin/python the variable $HOME is not being evaluated. My cron log has an entry that says "path not found".

Can someone enlighten me? Thanks!

Ugur
  • 1,914
  • 2
  • 25
  • 46

1 Answers1

4

Within crontab files, lines that look like VAR=value are definitions recognized by cron and not executed under a shell. So the value of a variable definition is not expanded in any way.

On the other hand, the command in a crontab entry, gets executed by the default crontab shell or, in your case, by the shell defined with the SHELLvariable.

Beware also that particular cron versions may not let you define arbitrary variables, but only particular ones like SHELL, HOME, MAILTO, etc. See Variables in crontab?.

Javier Elices
  • 2,066
  • 1
  • 16
  • 25
  • So is my approach basically wrong? Should I put the details and the path setting into a bash script and call that script from within the cronjob instead of setting the path in the crontab etc? And if so: Where should that script reside? In my Python project folder? – Ugur Oct 29 '17 at 19:15
  • Particular *cron* versions may not let you define variables, but I think that most will. So use your approach of defining variables to make the *crontab* entries clearer. Only, do not use a variable to define (part of) another... – Javier Elices Oct 29 '17 at 21:01
  • 1
    Also, for what it may be worth, I usually define a *bash* (shell) script to invoke a program from *crontab*. At the head of the script I define variables as I need to and then invoke the program (in your case Python). That gives you a place to prepare files, clean them and so on. – Javier Elices Oct 29 '17 at 21:03