我和Debian有一个树莓派。我也在运行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当我用suo执行的时候
pi@raspberrypi:~/domoticz/scripts $ sudo /home/pi/domoticz/scripts/domoticz_state_checker.sh我得到的结果与我通过cron运行脚本时的结果相同
你知道这里出了什么问题吗?我的cronjob在哪个帐户下执行?
发布于 2018-01-11 16:05:28
我认为要在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
您可以从所有用户的spool where文件中找到crontab
cat /var/spool/cron/crontabs/<user>
https://stackoverflow.com/questions/48189316
复制相似问题