SyntaxStudy
Sign Up
Linux / Bash System Cron Directories and Logging
Linux / Bash Beginner 1 min read

System Cron Directories and Logging

Beyond user crontabs, Linux provides a set of system-wide drop-in directories that make it easy to deploy scheduled scripts without editing crontab files directly. The `/etc/cron.d/` directory holds crontab-format files with an additional username field. The directories `/etc/cron.hourly/`, `/etc/cron.daily/`, `/etc/cron.weekly/`, and `/etc/cron.monthly/` run any executable scripts placed within them at the respective intervals. Cron sends the output of jobs as email to the user unless redirected. In most server environments, mail delivery is not configured, so output is silently discarded. Always redirect stdout and stderr explicitly in cron job commands. Log files should be written to `/var/log/` or an application-specific log location with appropriate log rotation configured. Debugging cron jobs can be challenging because they run in a stripped-down environment. Common issues include commands that work interactively but fail in cron due to missing environment variables or relative path references. The `/var/log/syslog` or `/var/log/cron` file logs cron activity. Testing a script with `env -i /bin/bash --noprofile --norc` simulates the cron environment.
Example
# ---- System cron directories ----

# List scripts in each directory
ls /etc/cron.d/
ls /etc/cron.daily/
ls /etc/cron.weekly/
ls /etc/cron.monthly/
ls /etc/cron.hourly/

# Add a daily maintenance script
sudo cp /usr/local/bin/cleanup.sh /etc/cron.daily/cleanup
sudo chmod +x /etc/cron.daily/cleanup

# /etc/cron.d/ format (includes username field)
# cat /etc/cron.d/myapp:
# PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# 0 * * * * www-data /usr/local/bin/myapp_hourly.sh >> /var/log/myapp.log 2>&1

# /etc/crontab format (also includes username)
cat /etc/crontab

# ---- Logging cron output ----

# Good practice: always redirect in cron
# 30 2 * * * /usr/bin/backup.sh >> /var/log/backup.log 2>&1

# Timestamped logging in the script itself
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; }
# Then call: log "Backup started"

# View cron log entries
grep CRON /var/log/syslog
grep CRON /var/log/syslog | tail -50

# On systems with dedicated cron log
cat /var/log/cron     # RHEL/CentOS/Fedora

# ---- Test script in cron-like environment ----
# Simulate minimal cron environment
env -i HOME=/home/alice USER=alice \
    PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin \
    /bin/bash -c '/usr/local/bin/myscript.sh'

# Run a cron job manually to test
run-parts --test /etc/cron.daily
run-parts /etc/cron.daily      # Actually runs them