0

I am trying to use cron on my debian11 VM to create a folder with todays date on system reboot if it does not already exist, this is the line I have used.

@reboot /usr/bin/mkdir -p /home/bin/data/"$(date '+%Y%m%d')"

This work from the terminal, and after looking online I understand the issue is that cron is not ran like a shell, and that I could solve this problem by packaging this line inside a .sh file. I'm ok with this solution but in the interest of simplicity and learning, how would I rewrite this line so it would run from cron successfully?

GKelly
  • 87
  • 8
  • 1
    Try a backslash before each `%`. – Mark Setchell Apr 03 '23 at 09:59
  • Yes thats solved it thanks! The backslash acts as an escape character, but why is this needed when it has been specified that a command will follow (the $")? – GKelly Apr 03 '23 at 10:04
  • 1
    Sorry, I can't give you an explanation. I just know that's the way it gets parsed. We'll have to wait together and see if someone clever comes along... – Mark Setchell Apr 03 '23 at 11:06
  • 1
    From `crontab` man page: "The sixth field of a line in a crontab entry is a string that shall be executed by sh at the specified times. A character in this field shall be translated to a . Any character preceded by a (including the '%') shall cause that character to be treated literally. Only the first line (up to a '%' or end-of-line) of the command field shall be executed by the command interpreter. The other lines shall be made available to the command as standard input." The '%' are converted to newlines before the shell quotes are applied. – William Pursell Apr 03 '23 at 14:21

1 Answers1

1

Escape percent-signs (%) in your command with backslash (\) character:

@reboot /usr/bin/mkdir -p /home/bin/data/"$(date '+\%Y\%m\%d')"

Refer to crontab(5):

The "sixth" field (the rest of the line) specifies the command to be run. The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile. 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.

kylethedeveloper
  • 78
  • 1
  • 2
  • 10
  • Please refrain from answering common duplicates; simply leave a comment pointing to one of the many existing questions about this problem. – tripleee Apr 03 '23 at 17:44