Cron fails on single apostrophe

前端 未结 3 1535
一整个雨季
一整个雨季 2021-02-08 19:37

The following does work as expected:

date +\'%d-%b-%Y-%H-%M\'

28-Sep-2009-14-28

But none of the following 4 entries from crontab are working.

* *         


        
3条回答
  •  暖寄归人
    2021-02-08 20:01

    There are four common causes for cron job commands to behave differently compared to commands typed directly into an interactive shell:

    • Cron provides a limited environment, e.g., a minimal $PATH, and other expected variables missing.
    • Cron invokes /bin/sh by default, whereas you may be using some other shell interactively.
    • Cron treats the % character specially (it is turned into a newline in the command).
    • The command may behave differently because it doesn't have a terminal available.

    You must precede all % characters with a \ in a crontab file, which tells cron to just put a % in the command, e.g.

    16 * * * * mysqldump myDB myTB > "/backup/ABCbc$(date +'\%d-\%b-\%Y-\%H-\%M').sql" 2> "/backup/ABCbc_errORS$(date +'\%d-\%b-\%Y-\%H-\%M').txt"
    

    (As a separate matter, always put double quotes around a "$variable_substitution" or a "$(command substitution)", unless you know why not do it in a particular case. Otherwise, if the variable contents or command output contains whitespace or ?*\[, they will be interpreted by the shell.)

提交回复
热议问题