22

In crontab, can you do something like this?

* * * * * echo $( date +%F) >> /path/date.txt
tripleee
  • 175,061
  • 34
  • 275
  • 318
JuanPablo
  • 23,792
  • 39
  • 118
  • 164
  • 1
    mail show me this. /bin/sh -c " echo $( date + /bin/sh: -c: line 0: unexpected EOF while looking for matching `)' /bin/sh: -c: line 1: syntax error: unexpected end of file – JuanPablo Mar 11 '11 at 19:54
  • That's a [useless use of `echo`](http://www.iki.fi/era/unix/award.html#echo), though. Anything which looks like `echo $(foo)` is better written simply `foo` (unless you specifically use an unquoted command substitution to cause the shell to normalize whitespace and expand wildcards in the output from `foo`). – tripleee Aug 30 '16 at 04:15

1 Answers1

36

The actual problem of your crontab line is not the $() or the backquotes. The problem is the percent sign %. It has a special meaning in crontabs.

From the manpage:

...
Percent-signs (%) in the command, unless escaped with backslash (\), 
will be changed into newline characters, and all data after the 
first % will be sent to the command  as standard input.
...

If you escape the percent sign with \ it should work as expected:

* * * * * echo $(date +\%F) >> /tmp/date.txt

or

* * * * * echo `date +\%F` >> /tmp/date2.txt

both work on my site.

bmk
  • 13,849
  • 5
  • 37
  • 46
  • 3
    Be aware that the backslashes are passed to the shell. So a command like the one above will work because the shell strips the backslash, but a backslash inside a string will be left in by the shell, as per http://www.hcidata.info/crontab.htm – Alastair Irvine Nov 27 '13 at 09:37
  • 3
    I hate cron with a vengeance – Willem Jun 03 '15 at 10:17