2

Possible Duplicate:
escaping double quotes and percent signs (%) in cron

I have the following command in cron:

5 6 * * * bash -c "tar -czf /backups/sites-server-files-rotate/sites_`date +%F`.tar.gz /backups/sites-server-files/"

But command doesn't get executed. And I can see the following in the cron log:

Apr 17 06:05:01 backup crond[9423]: (root) CMD (bash -c "tar -czf /backups/sites-server-files-rotate/sites_`date +)

It seems like % sign cuts the command in cron. Why? Do I have to escape it? And how?

  • @Kyle Smith Someone needs to rename that post to include % also. One can't find it using search. – Vladislav Rastrusny Apr 17 '12 at 11:34
  • Done. Though, I'm not sure you can search for a '%'. – Kyle Smith Apr 17 '12 at 12:18
  • OP, like me, asks "whyyyyyy?". It's because in crontab, percent is the WTF character. Seriously: I guess the rationale is so that cron can rely on task entries occupying only a single line of text file (to simplify parsing), but also needs a way to allow the entry field that contains "the command" to actually contain a sequence of two or more commands. Multi commands would normally be separated by "linefeeds", but can't be here as that would terminate the single line for this crontab entry... hence the use of percent to represent the linefeed between the multiple subsidiary commands. – gwideman Sep 06 '18 at 04:03

3 Answers3

3

Yes you do have to escape it. A backslash will do.

You can also put the command in a script and call the script instead.

Ladadadada
  • 26,787
3

Yes, you need to escape it. Just type \ backslash before every occurrence of %.

The percent character indicates new line in crontab.

Khaled
  • 36,903
  • What special meaning has % in cron? Or in shell? – Vladislav Rastrusny Apr 17 '12 at 11:03
  • @VladislavRastrusny "special meaning in cron": It's basically a way to cram multiple commands into a single line of the crontab text file. In crontab entries, there's evidently the need for the final field that contains the command to actually be able to contain a sequence of commands. If those multiple commands were separated as usual with a linefeed, the first such linefeed would end the overall crontab entry (and put the remaining sequential commands on separate lines) Hence the "special feature" where percent represents what would normally be the linefeed separating a sequence of commands. – gwideman Sep 06 '18 at 04:09
1

You can make a bash file with your script and then add it to crontab.

For example : make file script.sh

#!/bin/bash

tar -czf /backups/sites-server-files-rotate/sites_\`date +%F\`.tar.gz /backups/sites-server-files/

Then add to cron:

5 6 * * * /dir/to/your/script.sh
Ladadadada
  • 26,787
B14D3
  • 5,258