I want to execute all cronjobs in the environment defined in my ~/.zshenv, and I want to redirect STDOUT and STDERR of every cronjob to a single log file. I am on OS X 10.9. What is the cleanest way to achieve this?

  • does your crontab define the SHELL variable, to path to zsh on your systems?
    – llua
    Commented Sep 9, 2014 at 16:51
  • @llua No, my crontab does not define any environment variables. If I define an environment variable at the top of my crontab will it be used for all cronjobs? Commented Sep 9, 2014 at 16:53
  • Yes, it will. man 5 crontab for more information.
    – llua
    Commented Sep 9, 2014 at 17:04
  • @llua OK, so if I set SHELL to point to zsh then my zsh startup files will be loaded before every cronjob? Commented Sep 9, 2014 at 20:50

1 Answer 1


~/.zshenv is loaded by zsh when it starts (except when started with -f or if the configuration directory is changed by setting ZDOTDIR). It is not loaded (cannot be understood) by any other shell. So arranging load ~/.zshenv is equivalent to arranging for your jobs to be executed by zsh. Set the SHELL variable in the crontab; this applies to every job.

Beware of putting things on .zshenv, because it is read by every shell. For example, if you set an environment variable to execute some programs in a different environment (e.g. you want different versions of some files or programs, so you set some …PATH environment variables), this won't work if your .zshenv overrides these variables.

In particular, if you want to set environment variables for both your interactive sessions and cron jobs, don't use .zshenv. Use a file which you source from both ~/.profile and crontabs. Start every cron job with . ~/.my_environment.sh; (you can't do that globally).

Output from cron jobs is emailed to you using the local mail facility. I don't know how that's set up on OSX. I don't recommend using a log file instead, because cron takes care of sending an email per job and of not sending an email from successful jobs (no output, return code 0)). If you really want to use a log file, start each job with something like exec >~/cron-logs/nameofthisjob-$(date +\%Y\%m\%d-\%H\%M) 2>&1 &&.

  • Thanks for this solid answer. Am I correct in thinking that I could avoid running ~/my_environment.sh in every cronjob by creating a different .zshenv in some alternative directory and setting $ZDOTDIR to that directory in the crontab? Then I could source the environment from both .zshenvs. And just to confirm, there is no global setting that allows an alternative cron reporting method to email? Commented Sep 10, 2014 at 16:18
  • @SeanMackesey Indeed, if you set ZDOTDIR in the crontab, and you also set SHELL=/path/to/zsh, then $ZDOTDIR/.zshenv will be loaded at the start of every job. Commented Sep 10, 2014 at 16:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .