crontab運行腳本存在兩大問題:環境變量和路徑,從而導致單獨運行腳本沒問題,但用crontab運行就報錯。
1、環境變量
描述問題:crontab: usage error: no arguments permitted after this option
因為crontab不提供環境,所以需要自己在shell中加入,或者全部用絕對路徑。簡單的方法:控制台輸入
[user@a ~]# echo $PATH /your/path/1:/your/path/2………………
然后在腳本中export
export PATH=/your/path/1:/your/path/2…………
2、路徑
描述問題:單獨運行時能夠找到文件,但crontab運行時找不到(諸如此類的問題)。
如果你在腳本中用到了${PWD}等涉及相對路徑的參數,就會出現這種問題。比如你的腳本放在/home/user/shell路徑下,腳本中寫的日志輸出路徑為${PWD}/shell.log,單獨運行腳本時你可以在/home/user/shell下找到shell.log,但用crontab運行時,shell.log就會出現在/home/user目錄下。可見,crontab運行shell時${PWD}中存儲的是不是腳本所在路徑,而是腳本執行用戶的home路徑。解決方法:使用絕對路徑/home/user/shell/shell.log或修改為${PWD}/shell/shell.log。
