crontab 和 echo 的奇怪問題

crontab 和 echo 的奇怪問題
$ echo -e "test1\ntest2" > logfile

$ echo -e "test1\ntest2" >> logfile

$ cat logfile
test1
test2
test1
test2

$ rm logfile

$ crontab -e
* * * * * echo -e "test1\ntest2" >> logfile

$ sleep 160

$ cat logfile
-e test1
test2
-e test1
test2

為什麼我會得到輸出-e? crontab 和 bash 都使用/bin/echo

答案1

他們可能是不是兩者都使用/bin/echo.使用的環境cron可能與您的互動環境不同。指定完整路徑以確保安全。

答案2

printf這是人們建議使用而不是為了便攜性的原因之一echo

* * * * * printf "test1\ntest2\n" >> logfile

cron使用的shellsh而不是 Bash。在我的系統上,sh確實是 Dash,但它echo沒有-e.所以-e就變成了另一個要輸出的字串。其他版本的 Bourne shell 或提供其功能的 shell 可能具有-e.

如果您echo在 中使用時沒有完整路徑crontab,您將獲得 shell 的內建echo而不是/bin/echo.在命令列上,如果您使用的是 Bash,則echo無需完整路徑即可獲得 Bash 的內建版本。

相關內容