I have a cronjob configured as follows:
0 * * * * php ~/ruta/archivo.php >> ~/log.txt
After performing archivo.php
a data synchronization, it returns two possible responses:
- The database was successfully updated
- The database is up to date
That saves it perfectly in the log.txt
but when I want to add the date of the command to the cron:
date +'%Y-%m-%d %T' // 2016-01-12 21:59:06
According to me, I would get something like the following:
0 * * * * php ~/ruta/archivo.php $(date +'%Y-%m-%d %T') >> ~/log.txt
But when I see the log, it doesn't save any data from the command date
, it shows me the impressions like the following:
La base de datos está actualizada
La base de datos está actualizada
La base de datos está actualizada
La base de datos se actualizó correctamente
La base de datos está actualizada
La base de datos está actualizada
...
Instead if I execute the following if it works as I expect:
echo 'Soy un texto: ' $(date +'%Y-%m-%d %T') >> ~/log.txt
The text in the log remains:
...
Soy un texto: 2016-01-12 21:59:06
You can combine the results of multiple commands with
{ }
. So, in your crontab:The php command is executing the file and then the second part
$(date +'%Y-%m-%d %T')
interprets it as an argument, not part of the execution.try
In this way:
date
is executed and its output is used as the second parameter of the php command.What you want you can (almost) achieve with :
Here the php and date commands are executed one after the other and the output of both goes to ~/log.txt
But there is a problem with this, which may or may not be significant to you. cron sends an e-mail when a cron job ends in error (exist status other than 0).
With the previous line if php returns a status other than 0 this will be hidden by the execution of date.
If receiving email on php error is important to you, you can create a script, for example in /usr/local/bin/php_with_date.sh :
Which you would invoke with:
The script saves the php output and the date in the log as you want. And its exit status will be the same as that of the php command.
There are subtle differences between running a command directly by typing from the shell and running it from a crontab line. One of these differences is that the signs
%
must be escaped with\
The example you present:
It would be as follows:
Then. the log.txt file according to the context would have this content: