When trying to timestamp crontab output logs, many developers encounter issues where the date command either doesn't execute or outputs literally as text. This happens because crontab handles variable expansion differently than the shell.
The correct way to declare and use date variables in crontab requires special escaping and command substitution syntax:
DATEVAR=$(date +\%Y\%m\%d_\%H\%M\%S)
* * * * * echo "$(date +\%Y\%m\%d_\%H\%M\%S) - Job started" >> /var/log/cron.log
On CentOS 6 systems, you need to account for:
# Method 1: Inline execution
* * * * * echo "date +\\%Y\\%m\\%d_\\%H\\%M\\%S - Task completed" >> /path/to/log
# Method 2: Using escaped variables
CRONLOG=/var/log/mycron.log
DATE_CMD="date +\\%Y\\%m\\%d_\\%H\\%M\\%S"
* * * * * echo "$($DATE_CMD) - Running backup" >> $CRONLOG
Here's a fully functional crontab example with timestamped logging:
# Environment variables must be declared above cron jobs
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
CRON_LOG=/var/log/cronjobs.log
# Date format: YYYYMMDD_HHMMSS
* * * * * echo "$(date +\%Y\%m\%d_\%H\%M\%S) - Minute job" >> $CRON_LOG
*/5 * * * * /usr/bin/logger -t CRON "$(date +\%Y\%m\%d_\%H\%M\%S) - Five minute job"
If your date variables still aren't working:
- Ensure your cron daemon is running:
service crond status
- Check log permissions:
chmod 666 /var/log/cronjobs.log
- Verify command path: Use full paths like
/bin/date
- Test commands directly in shell first
For better log management, consider naming log files with dates:
0 0 * * * /bin/touch /var/log/cron-$(date +\%Y\%m\%d).log
* * * * * echo "Job ran" >> /var/log/cron-$(date +\%Y\%m\%d).log
When setting up cron jobs, many developers want to include timestamps in their log outputs. However, crontab handles variable expansion differently than interactive shells, which leads to common frustration when variables don't expand as expected.
The correct way to include dynamic dates in cron job outputs requires either:
# Method 1: Direct command substitution in the cron line
* * * * * echo "$(date +'%Y%m%d_%H%M%S') running job" >> /var/log/cron.log
# Method 2: Escaped percent signs in crontab
DATEVAR=$(date +\%Y\%m\%d_\%H\%M\%S)
* * * * * echo "$DATEVAR running job" >> /var/log/cron.log
# In crontab -e
CRONLOG=/var/log/crontab.log
* * * * * echo "[$(date +\\%Y-\\%m-\\%d_\\%H:\\%M:\\%S)] Job started" >> $CRONLOG
*/5 * * * * /path/to/script.sh >> $CRONLOG 2>&1
The main issues developers encounter:
- Percent signs need escaping in crontab (use \\%)
- Variables defined in crontab don't use export
- Command substitution requires proper $(command) syntax
For more complex logging:
# Create timestamped log files
0 * * * * /usr/bin/python /scripts/backup.py > /var/log/backup/backup_$(date +\%Y\%m\%d-\%H\%M).log 2>&1
# Include process information
* * * * * echo "[$(date +\\%F_\\%T)] $$ $(basename $0) - Processing started" >> $CRONLOG