[英]SH Script working in console but not in Cronjob
我有一個Debian的Raspberry PI。 我也在運行Domoticz。 Domoticz有時會停止,我必須重新啟動服務。 我使用以下腳本(domoticz_state_checker.sh):
#!/bin/bash
echo 'Checking if Domoticz is running.'
DomoticzState=`sudo service domoticz.sh status`
#echo $DomoticzState
if [[ $DomoticzState == *"active (running)"* ]]
then
echo 'Domoticz is running. Nothing to do.'
elif [[ $DomoticzState == *"domoticz is not running ... failed!"* ]]
then
echo 'Domoticz is not running. Restarting Domoticz...'
sudo service domoticz.sh restart
echo 'Domoticz restarted.'
elif [[ $DomoticzState == *"active (exited)"* ]]
then
echo 'Domoticz active (exited). Restarting Domoticz...'
sudo service domoticz.sh restart
echo 'Domoticz restarted.'
elif [[ $DomoticzState == *"inactive (dead)"* ]]
then
echo 'Domoticz inactive (dead). Restarting Domoticz...'
sudo service domoticz.sh restart
echo 'Domoticz restarted.'
fi
當我以用戶Pi運行此腳本時,該腳本有效。 我這樣跑
pi@raspberrypi:~/domoticz/scripts $ /home/pi/domoticz/scripts/domoticz_state_checker.sh
我使用crontab創建了以下內容-e以將其作為cronjob運行
*/5 * * * * pi /home/pi/domoticz/scripts/domoticz_state_checker.sh >> /home/pi/domoticz/scripts/domoticz_state_checker.log 2>&1
在我的cron日志中,我看到正在執行的作業:
Jan 10 14:55:01 raspberrypi CRON[23498]: (pi) CMD (pi /home/pi/domoticz/scripts/domoticz_state_checker.sh >> /home/pi/domoticz/scripts/domoticz_state_checker.log 2>&1)
但是該腳本不會重新啟動我的Domoticz服務。 檢查已經完成,但是然后我的if和elif語句出現錯誤。 我在domoticz_state_checker.log中看到以下錯誤:
Checking if Domoticz is running.
/home/pi/domoticz/scripts/domoticz_state_checker.sh: 7: /home/pi/domoticz/scripts/domoticz_state_checker.sh: [[: not found
/home/pi/domoticz/scripts/domoticz_state_checker.sh: 10: /home/pi/domoticz/scripts/domoticz_state_checker.sh: [[: not found
/home/pi/domoticz/scripts/domoticz_state_checker.sh: 15: /home/pi/domoticz/scripts/domoticz_state_checker.sh: [[: not found
/home/pi/domoticz/scripts/domoticz_state_checker.sh: 20: /home/pi/domoticz/scripts/domoticz_state_checker.sh: [[: not found
當我與索執行
pi@raspberrypi:~/domoticz/scripts $ sudo /home/pi/domoticz/scripts/domoticz_state_checker.sh
與通過cron運行腳本時得到的結果相同
任何想法出什么問題了嗎? 我的cronjob使用哪個帳戶執行?
我認為要以特定用戶身份在cronjob中運行shell腳本,您應該在crontab中使用-u
選項。
crontab -u pi -e
在位置文件之前添加命令bash
或/bin/bash
#<timing> <user> <command>
*/5 * * * * bash /home/pi/domoticz/scripts/domoticz_state_checker.sh >> /home/pi/domoticz/scripts/domoticz_state_checker.log 2>&1
您可以從后台打印文件中找到所有用戶的crontab文件
cat /var/spool/cron/crontabs/<user>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.