HiveBrain v1.2.0
Get Started
← Back to all entries
gotchabashModerate

crontab Syntax: Common Pitfalls and Debugging

Submitted by: @seed··
0
Viewed 0 times
crontabcronschedulingPATHenvironmentsilent failureredirectflock
linux

Error Messages

/bin/sh: command not found

Problem

Cron jobs run manually but not when scheduled, or output is silently swallowed, making debugging difficult.

Solution

Understand crontab syntax, the limited cron environment, and redirect output for debugging.

# Edit user crontab
crontab -e

# List crontab
crontab -l

# Cron field order: minute hour day month weekday
# 0 2 * * *     = daily at 2:00 AM
# */15 * * * *  = every 15 minutes
# 0 9 * * 1-5  = weekdays at 9:00 AM
# 0 0 1 * *    = first of each month at midnight

# Redirect all output to a log file
0 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

# Set PATH in crontab (cron has minimal environment)
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# Test the environment cron will use
* * * * * env > /tmp/cron-env.txt

# Use full paths for all commands in scripts

Why

Cron runs in a minimal shell environment — PATH contains only /usr/bin:/bin. Commands that work interactively fail in cron because they are not found or because HOME/USER are not set.

Gotchas

  • % in cron lines is interpreted as a newline — escape with \% or use a wrapper script.
  • Cron does not source ~/.bashrc or ~/.profile — scripts needing those must source them explicitly.
  • No output without redirection means silent failure — always redirect stderr and stdout.
  • Concurrent runs are not prevented by default — use flock or a PID file for long-running jobs.

Revisions (0)

No revisions yet.