Cron environment variables and PATH

On this page

A cron job does not inherit your login shell. According to the crontab manual, cron sets SHELL to /bin/sh and takes LOGNAME and HOME from the account entry; anything else you need, such as PATH, must be set in the crontab or in the command.

What does cron set?

VariableValue under cron
SHELL/bin/sh, unless the crontab sets it
LOGNAMEFrom the account line of the crontab's owner
HOMEFrom the account line, unless the crontab sets it
MAILTONot set by cron; if set in the crontab it chooses who gets the job output. Empty means no mail.

The crontab file may start with lines of the form NAME=value. They apply to every job below them, and they are not shell commands, so one variable cannot be built from another there.

Why does a command work in my shell and not in cron?

  • The command lives in a directory that only your profile adds to PATH, such as a version manager's shims or /usr/local/bin on a minimal system.
  • It reads a variable you export in .bashrc or .profile, which cron never loads.
  • It needs a terminal, a display or an ssh agent that a background job does not have.
  • It assumes a working directory. Cron starts jobs in the home directory; use cd /path && command or absolute paths.

How do I fix it?

crontab
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=""

15 3 * * * cd /srv/app && ./bin/nightly && curl -fsS --retry 5 https://ping.cronmissed.com/5f0c1b2e-7a3d-4c8e-9b61-2d4f8a7e3c10

To see the environment cron gives a job, add a temporary line such as * * * * * env > /tmp/cron-env.txt and compare the file with the output of env in your shell. Remove it once you have the answer.

Sources

Questions and answers

Should I put source ~/.profile in the cron line?
It works, but it hides which variables the job needs and it breaks when the profile changes. Setting the few variables you need in the crontab keeps the job explicit.
Does a systemd service have the same problem?
Yes, in a different form: a service gets a clean environment too. Set Environment= or EnvironmentFile= in the unit.
Know the moment a job goes quiet

Create a check, add one curl to the job, and CronMissed alerts you when a ping is late or reports a failure.

Start monitoring