Sub topic 3
Cron's minimal environment and how to work with it
This chapter assumes you can edit a crontab, write a basic shell script, and read exit codes. It covers what a cron job actually sees when it runs, why scripts that work in your terminal fail under cron, and how to make a job's environment explicit and predictable.
Why "it works in my shell" is not enough
When you log in, your shell reads startup files such as /etc/profile, ~/.profile, ~/.bash_profile and ~/.bashrc. These files set PATH, load language version managers, export credentials and define aliases. Cron reads none of them.
Cron starts each job as a non-interactive, non-login process with a small, fixed environment. A script tested by hand can therefore fail under cron in these ways:
- A command is "not found" because
PATHis shorter. - A variable such as
AWS_PROFILEorDATABASE_URLis empty. - A relative path points to the wrong place because the working directory is the user's home directory.
- A tool behaves differently because
LANGorTZdiffers. - A command asks for a terminal and finds none.
Because cron has no terminal, these failures often appear only as a mail message that nobody reads, which connects to the silent-failure problem from the first chapter.
What cron actually provides
A typical Vixie-cron or cronie job starts with roughly this environment:
| Variable | Typical value under cron | Notes |
|---|---|---|
| `HOME` | The home directory of the crontab's owner | Taken from `/etc/passwd` |
| `LOGNAME` and `USER` | The crontab's owner | Set by cron |
| `SHELL` | `/bin/sh` | Not bash, even if your login shell is bash |
| `PATH` | `/usr/bin:/bin` | Excludes `/usr/local/bin` and `/sbin` on many systems |
| Working directory | `HOME` | Not the directory the script lives in |
Exact defaults vary by distribution and cron implementation. Debian and Ubuntu historically use /usr/bin:/bin, while some Red Hat family systems use a slightly longer list. Do not memorize a value. Print it on your own system, as shown below.
See the environment for yourself
The most reliable way to learn what cron provides is to ask cron. Add a temporary job that dumps its environment, wait one minute, then remove it.
# Add temporarily with: crontab -e
* * * * * /usr/bin/env | /usr/bin/sort > /tmp/cron-env.txt 2>&1After a minute, compare the result with your interactive shell:
env | sort > /tmp/shell-env.txt
diff /tmp/shell-env.txt /tmp/cron-env.txtThe diff lists every variable your script might depend on without your noticing. Remove the temporary crontab line when you are done. The file in /tmp may contain secrets from your shell environment, so delete it too.
Setting variables in a crontab
A crontab file may contain variable assignments before or between job lines. Cron applies them to the jobs in that file.
# user crontab (edit with: crontab -e)
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
[email protected]
LANG=en_US.UTF-8
30 2 * * * /usr/local/bin/backup.shThe rules for these lines are narrow, and they cause many mistakes:
- The format is
NAME=value. Spaces around=are allowed in most implementations, but quotes are optional and are removed only when they surround the whole value. - There is no variable expansion.
PATH=$PATH:/opt/bindoes not append to the existing path. Cron treats$PATHas literal text. Write the full list. - There is no command substitution.
TODAY=$(date +%F)is not evaluated. - Assignments are not shell commands. They are read by cron itself, before the shell starts.
MAILTOis special. It tells cron where to send job output. An empty value (MAILTO="") disables mail.
Setting SHELL=/bin/bash changes the shell that runs the command column. Without it, a line like cmd1 && cmd2 || cmd3 works, but bash-only syntax such as [[ ... ]], process substitution or {1..5} fails under /bin/sh on Debian-based systems, where sh is dash.
The percent sign trap
In a crontab command, an unescaped % is turned into a newline, and everything after the first one is sent to the command as standard input. This breaks date formatting:
# Broken: cron truncates the command at the first %
0 1 * * * tar czf /backup/site-$(date +%F).tgz /var/www
# Correct: escape each percent sign
0 1 * * * tar czf /backup/site-$(date +\%F).tgz /var/wwwThe cleaner fix is to move logic into a script, where % has no special meaning. A crontab line should be short: a schedule and one command.
Make the script carry its own environment
Relying on crontab variables splits your configuration across two files. A more portable approach is to make the script set up what it needs. Then it behaves the same under cron, systemd, a manual run, or sudo.
#!/usr/bin/env bash
set -euo pipefail
# Fixed, explicit PATH instead of whatever the caller provided
export PATH=/usr/local/bin:/usr/bin:/bin
# Do not depend on the caller's working directory
cd "$(dirname "$(readlink -f "$0")")"
# Load configuration from a file with restricted permissions
config=/etc/sync/sync.env
if [[ -r "$config" ]]; then
set -a
. "$config"
set +a
fi
: "${DEST_HOST:?DEST_HOST must be set in $config}"
rsync -a --delete ./data/ "backup@${DEST_HOST}:/srv/backups/data/"Several choices here matter:
- Explicit
PATH. The script always finds the same tools. If you prefer, use absolute paths for every command instead. cdto a known directory. Relative paths now resolve the same way every time. Usereadlink -fso the result is correct even if the script is run through a symlink.- A separate environment file. Secrets and host-specific values live in
/etc/sync/sync.env, not in the crontab, wherecrontab -lwould show them to anyone with access. Set the file to mode0600and owned by the job's user. ${VAR:?message}. The script stops with a clear error if a required variable is missing. An empty variable should never silently turnrm -rf "$DIR/"intorm -rf /.set -aandset +a. Everything sourced between them is exported to child processes.
Interactive-only assumptions
Some tools only work when they can talk to a person. Check for these before you schedule a job:
- Terminal requirements. Commands that call
tty, usesudowithrequirettyconfigured, or prompt for confirmation fail without a terminal. Add non-interactive flags such as-yor--batch, and avoidsudoinside a job. Run the job as the right user instead. - SSH agents.
SSH_AUTH_SOCKis not set, so keys that rely on an agent are unavailable. Use a dedicated key without agent forwarding, restricted on the remote side with a forced command orfrom=option. - Shell aliases and functions. These come from
.bashrcand do not exist. Call the real command. - Version managers. Tools such as
nvm,pyenvandrbenvmodifyPATHfrom shell startup files. Point to the interpreter directly, for example/home/app/.pyenv/versions/3.12.1/bin/python, or use a virtual environment'sbin/python.
Crontab locations and the user field
Where you put a job decides which environment rules and syntax apply.
| Location | Has a user field | Typical use |
|---|---|---|
| `crontab -e` (per-user) | No | Jobs for one account |
| `/etc/crontab` | Yes | System-wide jobs, edited by hand |
| `/etc/cron.d/*` | Yes | Jobs shipped by packages or configuration management |
| `/etc/cron.hourly`, `.daily`, `.weekly`, `.monthly` | Not applicable | Executable scripts run by `run-parts` or anacron |
In /etc/crontab and /etc/cron.d, the sixth field is the user name:
# /etc/cron.d/sync
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
[email protected]
*/15 * * * * backup /usr/bin/flock -n /run/lock/sync.lock /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1Files in /etc/cron.d must be owned by root and not writable by others. On Debian-based systems, file names may contain only letters, digits, underscores and hyphens. A name such as sync.conf is silently ignored because run-parts style name rules skip names with dots. Scripts in cron.daily and its siblings follow the same naming rule, and they must be executable.
Where output goes
Cron collects anything the job writes to standard output or standard error. If there is any output, it mails it to MAILTO, or to the crontab's owner if MAILTO is not set. On many servers no mail transfer agent is installed, so the message is lost without any visible error.
Two practices cover this, and the next chapters build on them:
- Redirect output to a log file explicitly, as in
>> /var/log/sync.log 2>&1. The order matters.2>&1must come after the file redirection, or standard error still goes to the mail path. - Make the job's exit status mean something, so a monitor can act on it.
Debugging an environment problem
When a job works by hand but fails under cron, work through these steps in order:
- Read the log or mail output for "command not found" or "No such file or directory".
- Dump the cron environment as shown earlier and diff it against your shell.
- Reproduce cron's conditions manually by running the job with a stripped environment:
env -i HOME="$HOME" LOGNAME="$USER" SHELL=/bin/sh PATH=/usr/bin:/bin \
/bin/sh -c '/usr/local/bin/sync.sh'- Run the command as the job's user, not as yourself, with
sudo -u backup. File permissions andHOMEdiffer. - Check that cron saw the job at all. On systemd-based distributions, run
journalctl -u cron(Debian family) orjournalctl -u crond(Red Hat family). Look forCMDlines that show the command was started.
env -i clears every variable, which is stricter than cron, so passing it is a good sign. It does not reproduce the missing terminal or the working directory, so it is a close approximation, not a guarantee.
Summary of rules
- Never assume
PATH,HOME, the working directory, or the shell. Set them in the script or crontab. - Do not expect expansion in crontab assignments.
- Escape
%in crontab commands, or move the logic into a script. - Keep secrets out of crontabs, in a file with tight permissions.
- Redirect output deliberately, because mail often goes nowhere.
Exercise
A crontab line 0 3 * * * pg_dump mydb | gzip > /backup/db-$(date +%F).sql.gz never creates a file, and a similar script that you run by hand works. Name two separate problems that could be causing it and how you would fix each.
Show answer
First, the unescaped % in date +%F is turned into a newline by cron, which truncates the command. Fix it by writing \%F, or better, move the command into a script. Second, pg_dump may not be on cron's short PATH (often /usr/bin:/bin), and the job may run as a user without database access. Fix it by setting PATH in the crontab or script, or using the full path to pg_dump, and by running the job as the correct user. Also redirect standard error to a log file so the failure message is not lost.
Exercise
Why does PATH=$PATH:/opt/tools/bin at the top of a crontab not add /opt/tools/bin to the existing path, and what should you write instead?
Show answer
Cron reads assignment lines itself and does not expand variables or run commands in them, so $PATH is taken as literal text. Write the complete value, for example PATH=/opt/tools/bin:/usr/local/bin:/usr/bin:/bin.