Linux Basic — cron Environment

1 minute read

cron Environment

Jobs run by cron have a minimal environment — no shell profile, no $PATH from your interactive session. This is the source of 90% of “it works manually but not in cron” bugs.


Default cron Environment

Variable Typical Value
SHELL /bin/sh (or /bin/bash on some distros)
PATH /usr/bin:/bin (minimal!)
HOME user’s home directory
LOGNAME / USER username
MAILTO username (mail output to this address)

Notably missing: aliases, functions, ~/.bashrc settings, custom $PATH additions.


Setting Variables in crontab

Add variable assignments before your job lines:

SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=ops@example.com

0 2 * * * /opt/backup.sh

These apply to all subsequent jobs in that crontab.


Per-Job Environment

Set a variable for one job by prefixing the command:

0 2 * * * PATH=/custom/bin:$PATH /opt/backup.sh

Or source an env file:

0 2 * * * . /etc/myapp/env && /opt/backup.sh

MAILTO — Controlling Email

By default, cron emails any output (stdout/stderr) to the user. Useful for errors, noisy for normal runs.

# email output to ops
MAILTO=ops@example.com

# disable email entirely
MAILTO=""

# per-job: redirect to log
0 2 * * * /opt/backup.sh >> /var/log/backup.log 2>&1

If MAILTO is unset or set to the username, cron sends mail to the local user.


Debugging “command not found”

If your script works in the shell but not in cron:

  1. Check PATH — add the directory with your command to PATH= in crontab
  2. Use absolute paths — /usr/local/bin/myapp instead of myapp
  3. Echo the environment — add a test job: * * * * * env > /tmp/cronenv.txt

Compare /tmp/cronenv.txt to your shell’s env output.


Example: Full crontab with Environment

# crontab for automated jobs
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin:/opt/scripts
MAILTO=ops@example.com

# daily backup
0 2 * * * /opt/scripts/backup.sh

# hourly health check (no email on success)
0 * * * * /opt/scripts/health-check.sh >/dev/null 2>&1

# weekly report
0 8 * * 1 /opt/scripts/weekly-report.sh

Next → Logging Cron Output

Updated: