天天看點

crontab條目包含%号問題

crontab條目中包含%号,最常見的取時間,如:date +%d,

對%需要使用\進行轉義,否則不能按預期執行,正确做法為:

* * * * * echo "`date +\%d`" > /tmp/r1r.txt

而不能為

* * * * * echo "`date +%d`" > /tmp/r1r.txt

%是crontab的特殊字元,所有%後的被當作了标準輸入,這可以通過“ man 5 crontab”檢視到說明:

The entire command portion of the line, up to a newline or a "%" character,

will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile.

A "%" character in the command, unless escaped with a backslash (\), 

will be changed into newline char-acters,

and all data after the first % will be sent to the command as standard input.

示例:

$ cat /tmp/hello.txt 

cat: /tmp/hello.txt: 沒有那個檔案或目錄

$ echo -e "`crontab -l`\n* * * * * cat > /tmp/hello.txt % hello word"|crontab -

$ crontab -l|grep hello.txt

* * * * * cat > /tmp/hello.txt % hello word

 hello word