# Fix Crontab Percent Sign (%) Syntax Errors and Missing EOF Newline Silent Skips

> 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.

- **Canonical URL**: https://opslint.dev/cron/crontab-percent-sign-newline-eof-pitfalls/
- **Category**: `CRON`
- **Interactive Workbench**: [Open in Live Workbench](https://opslint.dev/cron/#expr=0%202%20*%20*%20*&tz=UTC)
- **Normative Specifications**: `POSIX.1-2017 crontab Command Field Percent-Sign Semantics`, `Vixie Cron 4.1 crontab(5) % Newline & EOF Requirements`

## Incident Symptom & Root Cause

**Production Symptom**: A backup command like pg_dump mydb > /backups/db-$(date +%F).sql works every time in an interactive SSH session, but fails every night inside crontab with /bin/sh: 1: Syntax error: Unterminated quoted string or unexpected EOF while looking for matching ')'. Or the final line of /etc/crontab never runs at all.

**Protocol / Engine Root Cause**: Per POSIX crontab(5), the cron daemon replaces EVERY unescaped percent character (%) in the command field with a literal newline character before executing /bin/sh -c: only text before the first % is passed to the shell, and everything after the first % is piped to the command's standard input (stdin)! Separately, Vixie Cron requires every crontab entry—including the last line of the file—to end with a newline (\n) before EOF.

## Remediation Diff (Broken vs Verified Fix)

### Broken /etc/cron.d/backup File (Two Silent Killers!)

```text
# BUG 1: Unescaped '%' splits command at 'date +', feeding 'F).sql' to stdin!
0 2 * * * postgres pg_dump appdb > /var/backups/appdb-$(date +%F).sql

# BUG 2: File saved without trailing newline (
) at EOF -> line ignored by crond!
30 3 * * * root /usr/local/sbin/prune-wal.sh<EOF-WITHOUT-NEWLINE>
```

### Escaped \% in Crontab (or Wrapper Script) + Trailing Newline

```text
# Fix Option A: Escape EVERY '%' as '%' inside crontab / /etc/cron.d/* files:
0 2 * * * postgres pg_dump appdb > /var/backups/appdb-$(date +%Y-%m-%d).sql
30 3 * * * root /usr/local/sbin/prune-wal.sh
# ^ Ensure file ends with a trailing newline (
)!

# Fix Option B (Best Practice): Move date formatting & redirects into a versioned script
# /usr/local/bin/backup-appdb.sh (where normal bash '%' needs ZERO escaping!):
0 2 * * * postgres /usr/local/bin/backup-appdb.sh
```

## Engineering Deep Dive

The percent-sign rule dates back to Seventh Edition Unix (1979) to allow inline multi-line mail bodies inside crontab without external files (for example: 0 9 * * 1 mail ops%Subject: Weekly check%All systems nominal). Because POSIX standardized that historical behavior, Vixie Cron, Cronie, and BSD cron all scan the sixth (or seventh in /etc/crontab) field and convert every unescaped % into \n, passing only the prefix before the first % to /bin/sh -c!

Escaping mismatches also strike in the reverse direction when teams copy a working crontab line INTO Kubernetes CronJob YAML, GitHub Actions run: steps, or systemd ExecStart=! None of Kubernetes, GitHub Actions, or systemd performs crontab % newline substitution—so copying date +\%F literally into a Kubernetes Pod command passes a literal backslash to date, printing \2026-11-27 into filenames! Moving any command containing date formats, pipes, or conditionals into an executable script file with set -euo pipefail eliminates escaping differences across all schedulers.

Finally, whenever provisioning /etc/crontab or /etc/cron.d/* via Ansible, Chef, Puppet, or Dockerfile echo/heredoc commands, check two file-level rules: (1) the file MUST end with a trailing newline character (tail -c 1 /etc/cron.d/myjob | od -c should show \n), and (2) files inside /etc/cron.d/ on Debian/Ubuntu run-parts ignore filenames containing dots (such as my-backup.cron—name it /etc/cron.d/my-backup without an extension and chmod 0644 owned by root!).

## Crontab File & Escaping Pitfalls Checklist

| Case / Engine | Protocol Behavior | Production Remediation |
| :--- | :--- | :--- |
| **Unescaped % in crontab / /etc/cron.d/*** (`#crontab-unescaped-percent`) | First % terminates shell command; text after % becomes stdin data, breaking $(date +%F) or SQL LIKE '%foo%'. | Escape as \% in crontab, or move logic into a standalone .sh script. |
| **Copying \% into K8s YAML / GitHub Actions** (`#k8s-gha-overescaped-percent`) | Backslash is NOT stripped by K8s or GitHub Actions; date outputs literal '\2026-11-27'. | Use plain +%Y-%m-%d (no backslash) in Kubernetes, GitHub Actions, and systemd. |
| **Missing \n at end of crontab file** (`#crontab-missing-eof-newline`) | Vixie Cron refuses to load or silently drops the final line without a terminating newline. | Always end /etc/crontab and /etc/cron.d/* files with a newline; crontab -e enforces this. |
| **/etc/cron.d/backup.cron (dot in filename) or 0664 perms** (`#etc-crond-dot-filename`) | Debian/Ubuntu cron ignores /etc/cron.d files with dots in the name or group-writable perms. | Name /etc/cron.d/app_backup (only [a-zA-Z0-9_-]), owner root:root, mode 0644, plus username column! |

## Frequently Asked Engineering Questions

### Why did a file I dropped into /etc/cron.d/ fail with 'Error: bad username; while reading /etc/cron.d/myjob'?

Unlike user crontabs edited via crontab -e (which have 5 time fields + command), system files in /etc/crontab and /etc/cron.d/* MUST include a 6th 'username' field (such as root or www-data) between day-of-week and the command!

### How does systemd handle % inside ExecStart=?

systemd treats % as a unit specifier prefix (%i instance name, %h home dir, %H hostname)! To pass a literal % to date inside a systemd .service unit without a wrapper script, double the percent sign: ExecStart=/bin/sh -c 'date +%%F'.

### How can I audit /etc/cron.d/* in CI before deploying?

Verify three invariants in CI: [ -z "$(tail -c 1 "$f")" ] (trailing newline exists), filename matches ^[a-zA-Z0-9_-]+$, and grep -P '^[^#]*[^\\]%' "$f" returns zero unescaped percent signs.

## Related Problem-Cluster Guides

- [Fix Cron Jobs That Work in Terminal SSH But Fail Silently in Crontab (PATH, SHELL, Env)](https://opslint.dev/cron/cron-environment-path-locale-silent-failures/) — Diagnose why cron runs with minimal PATH=/usr/bin:/bin, /bin/sh (dash) instead of bash, missing SSH/cloud credentials, and C locale.
- [The POSIX Cron Day-of-Month + Day-of-Week OR Trap (0 9 13 * 5 Runs Every Friday)](https://opslint.dev/cron/posix-dom-dow-or-boolean-trap/) — Why specifying both Day-of-Month and Day-of-Week in POSIX crontab evaluates as boolean OR (union) instead of AND, and how to guard intersection schedules.
- [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.
- [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.
