Add date to filename in cron
Created: Last updated:
When you run some scripts in Linux with a cron job you will add this to crontab and may want to redirect the output to log file. Adding a date to this log's filename is a little tricky in crontab. Let me show you how it works.
Command Line (CLI)
Adding a date to a filename for a output redirect on the command line is fairly easy. It goes like this:
echo 'Hello world' > /var/log/somelog`date +%Y%d%m`.log
You simple put the date command with its parameters in grave accents, usually called single back quotes or back-ticks. This is known as command substitution. The problem is this doesn't seem to work in crontab but there is just a little trick you need to know and it will work just fine in a cron job too.
date command in cron
The date command in cron tab works exactly the same but the percent sign (%) we have for the date format is the problem. The percent sign has a special meaning in cron and this is throwing off the whole thing and actually causing the whole cron job to fail. The easy solution is to escape the percent sign with a backslash.
Some backslash to escape the % sign is all that is required.