# Fix Cron Jobs That Work in Terminal SSH But Fail Silently in Crontab (PATH, SHELL, Env)

> Diagnose why cron runs with minimal PATH=/usr/bin:/bin, /bin/sh (dash) instead of bash, missing SSH/cloud credentials, and C locale.

- **Canonical URL**: https://opslint.dev/cron/cron-environment-path-locale-silent-failures/
- **Category**: `CRON`
- **Interactive Workbench**: [Open in Live Workbench](https://opslint.dev/cron/#expr=*/15%20*%20*%20*%20*&tz=UTC)
- **Normative Specifications**: `POSIX.1-2017 crontab Default Shell Environment (SHELL, PATH, HOME)`, `Vixie Cron 4.1 crontab(5) Non-Interactive Environment Parsing`

## Incident Symptom & Root Cause

**Production Symptom**: Running /opt/scripts/deploy-sync.sh manually over SSH succeeds every time, yet when scheduled in crontab it silently produces 0-byte outputs or fails with command not found for aws, kubectl, node, docker, jq, or python3 installed in /usr/local/bin, ~/.local/bin, or nvm/pyenv paths.

**Protocol / Engine Root Cause**: Cron spawns a non-login, non-interactive /bin/sh process (which is dash on Debian/Ubuntu, NOT bash!) with a stripped environment: PATH=/usr/bin:/bin, HOME, LOGNAME, and SHELL=/bin/sh. It NEVER sources /etc/profile, ~/.bashrc, ~/.bash_profile, ~/.zshrc, SSH agent sockets, or Docker container runtime env vars!

## Remediation Diff (Broken vs Verified Fix)

### Interactive-Shell Assumptions Inside Crontab

```text
# Fails on 4 counts:
# 1. Default SHELL=/bin/sh rejects bash 'source' and '[[ ... ]]' syntax!
# 2. PATH=/usr/bin:/bin misses /usr/local/bin/aws and /usr/local/bin/jq!
# 3. stderr discarded or sent to local dead /var/mail/spool with no alerting!
*/15 * * * * source ~/.bashrc && aws s3 sync /data s3://my-bucket | jq .
```

### Explicit Crontab Header + Self-Contained Wrapper Script

```text
# Top of crontab / /etc/cron.d/data-sync:
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LANG=C.UTF-8

# Log stdout+stderr via logger to syslog/journald and surface non-zero failures:
*/15 * * * * /opt/scripts/s3-sync.sh 2>&1 | /usr/bin/logger -t s3-sync

# Inside /opt/scripts/s3-sync.sh (chmod 0755):
# #!/usr/bin/env bash
# set -euo pipefail
# export AWS_REGION="us-east-1"
# /usr/local/bin/aws s3 sync /data s3://my-bucket --only-show-errors
```

## Engineering Deep Dive

Ninety percent of 'cron didn't run' tickets are actually 'cron ran right on schedule, failed on line 2 in 4 milliseconds with command not found, and wrote the error to an unread local mbox or nowhere at all.' Check journalctl -u cron (Debian/Ubuntu) or journalctl -u crond (RHEL/Amazon Linux) first to confirm crond invoked CMD; once you see CMD (...) in syslog, the failure is guaranteed to be environment, permissions, working directory, or shell syntax.

Watch out for Vixie Cron's non-shell variable parser at the top of crontab files! Lines like PATH=/usr/local/bin:$PATH do NOT perform variable expansion in Vixie Cron: cron parses key=value literally (without a shell!), setting your PATH to the literal string '$PATH'! Always spell out the full static path list: PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin.

Inside Docker containers, cron environment isolation hits an extra wall: environment variables passed via docker run -e DATABASE_URL=... or Kubernetes Pod env: exist ONLY in PID 1's environment block—when Vixie crond forks a child job, crond wipes the environment down to PAM/default vars, erasing DATABASE_URL! In containers, avoid Vixie crond completely: either use Kubernetes CronJobs (one container run per schedule inheriting full Pod env) or use supercronic, which runs in foreground as PID 1, preserves 100% of container env vars, and streams structured logs directly to stdout/stderr.

## Interactive SSH vs Crontab Execution Environment Diff

| Case / Engine | Protocol Behavior | Production Remediation |
| :--- | :--- | :--- |
| **PATH Lookup** (`#env-path-minimal`) | Crontab defaults strictly to PATH=/usr/bin:/bin (misses /usr/local/bin, /snap/bin, ~/.cargo/bin, nvm). | Declare full static PATH=... at top of crontab (never write PATH=/foo:$PATH—$PATH is not expanded!). |
| **Default SHELL (/bin/sh vs /bin/bash)** (`#env-shell-dash`) | /bin/sh is dash on Ubuntu/Debian; bashisms like pipefail, [[ ]], arrays, and source fail. | Set SHELL=/bin/bash in crontab AND put #!/usr/bin/env bash + set -euo pipefail inside scripts. |
| **Current Working Directory (pwd)** (`#env-working-dir`) | Cron starts in the user's HOME directory (/root or /home/user), breaking relative ./config.json paths. | cd "$(dirname "$0")" at script start or use absolute filesystem paths everywhere. |
| **Docker / Container env vars (DATABASE_URL)** (`#env-docker-vars-stripped`) | Vixie crond strips PID 1 container environment variables when spawning cron children. | Use Kubernetes CronJob or supercronic in containers instead of background Vixie crond. |

## Frequently Asked Engineering Questions

### How can I reproduce the exact stripped environment cron uses from my interactive SSH terminal?

Run env -i HOME="$HOME" LOGNAME="$LOGNAME" PATH=/usr/bin:/bin SHELL=/bin/sh /bin/sh -c '/path/to/your/command'. Any missing binary, locale issue, or bashism will surface immediately in your terminal!

### Why did Python raise UnicodeEncodeError inside cron when printing UTF-8 characters?

Without LANG or LC_ALL set, minimal cron environments sometimes fall back to the POSIX 'C' ASCII locale on older distros. Add LANG=C.UTF-8 (or PYTHONIOENCODING=utf-8) at the top of your crontab or wrapper script.

### Why does MAILTO='' matter on servers without Postfix or Exim installed?

When a cron job writes anything to stdout or stderr and no MTA is installed, cron logs '(CRON) info (No MTA installed, discarding output)' and drops the error! Pipe output through /usr/bin/logger -t jobname so every line lands in systemd-journald.

## Related Problem-Cluster Guides

- [Fix Crontab Percent Sign (%) Syntax Errors and Missing EOF Newline Silent Skips](https://opslint.dev/cron/crontab-percent-sign-newline-eof-pitfalls/) — Why date +%Y-%m-%d crashes inside Linux crontab with unexpected EOF while succeeding in bash, and why missing trailing newlines drop the last cron job.
- [Prevent Overlapping Cron Jobs with Linux flock -n Non-Blocking Locks](https://opslint.dev/cron/flock-prevent-overlapping-cron-flock-wrappers/) — Stop runaway duplicate cron processes and database lock pileups using kernel-managed util-linux flock -n file descriptors instead of brittle PID files.
- [Kubernetes CronJob .spec.timeZone, CRON_TZ Rejection, and ConcurrencyPolicy Guide](https://opslint.dev/cron/kubernetes-cronjob-timezone-and-concurrency-policy/) — Configure IANA timezones safely in Kubernetes v1.27+ CronJobs, fix rejected CRON_TZ/TZ prefixes in .spec.schedule, and choose between Forbid and Replace.
- [systemd OnCalendar vs POSIX Cron: AND Logic, Reverse Offsets (~), and Persistent=true](https://opslint.dev/cron/systemd-oncalendar-to-cron-and-logic-differences/) — Avoid critical translation bugs between systemd.timer OnCalendar expressions and 5-field POSIX cron, including DOM+DOW intersection, seconds, and missed boot catch-up.
