I was playing aroudn with some variations of date like
DATE = $(date)
but that didnt work either
crontab -e
CRONLOG=/tmp/log/crontab.log
DATEVAR=`date +20\%y\%m\%d_\%H\%M\%S`
* * * * * echo $DATEVAR >> /tmp/log/crontab.log
*/2 * * * * echo "$DATEVAR hello" >> ${CRONLOG}
*/1 * * * * echo 'every minute' >> ${CRONLOG}
this just outputs the text as is...
I want to create a log entry in crontab.log with a timestamp on each update
How can I do this on CentOS 6?
UPDATE
DATEVAR=date +20%y%m%d_%H%M%S
*/1 * * * * /bin/echo [CRON] $($(DATEVAR)) >> /tmp/log/crontab.log
rendered only [CRON] and NOTHING when I tried it =/
Cron is not a shell - it does not parse commands in the same way that a shell does. As such, your variable is assigned as if it was static text.
There are three solutions I know of to this problem:
Option 1: Use a shell script to generate your command, include whatever variables and logic you want - and call that shell script from cron.
Where
myscript.sh
:Option 2: Include the date command directly in your command, and, since the entire command is passed to the shell, the date will be processed and replaced with an actual date.
Option 3: Set the string variable in cron, and pass that to your command to be processed (note - the percent signs do not need to be escaped, and the variable itself is wrapped in $() to execute it in a separate shell - backticks should work the same):
(In all the cases above, you can, of course, use a variable for the log path, instead of 'hard coding' it.)
The "problem" is that
cron
uses the percent sign as a special character. You have to quote it so it is ignored bycron
, but not by the shell. Like most of the folks who I saw that spent hours upon hours tinkering around with when and how and where to quote what, I went through that hack-and-slash as well.Here's the solution I found that has worked on all flavors of *nix:
As the old saying in the world of Perl: there is always more than one way to do it. I am not saying this is the only way or the best way -- what I am saying is that this works for crontab entries running on CentOS, Debian, Ubuntu, Mac, and AIX, so this is what am sticking with.
Just a working example of using variables in the
crontab
file and their substitution in the strings: