Score:0

Using quotes in variables of a crontab job

us flag

I'm trying to get a past date inside a cron job using something like this. But the DATE variable is always empty.

DATE=date -d "$date -1 days -1 months" +%Y-%m
* * * * * /bin/echo "Date: $($DATE) Test" >> /tmp/crontab.log 2>&1

I know how tricky crontab is thanks to this question with good answers, but the problem here doesn't seem to be the % sign, because the code above works fine:

DATE=date -d @2147483647 +%Y-%m
* * * * * /bin/echo "Date: $($DATE) Test" >> /tmp/crontab.log 2>&1

But if I use quotes, then the job again can't get the date.

DATE=date -d"@2147483647" +%Y-%m
* * * * * /bin/echo "Date: $($DATE) Test" >> /tmp/crontab.log 2>&1

I tried replacing quotes with single quotes, double quotes, escaping the quotes, but none of this options solved the problem. And I need quotes to specify the "$date -1 days -1 months" part. Is there a way to do this in crontab without creating an external script?

CentOS 7 and crontab (cronie-1.4.11-23.el7.x86_64)

Score:0
jp flag

The issue has nothing to do with cron but with variable expansion within $(). The date command called in the subshell $() doesn't see a parameter -d "$date -1 days -1 months" but multiple params instead: -d "$date -1 days -1 months. You probably want to use $(eval $DATE) instead.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.