SH脚本在控制台中工作,但在Cronjob中没有

时间:2018-01-10 14:12:34

标签: linux cron raspberry-pi debian

我有一个使用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创建了以下内容 - 以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在哪个帐户下执行?

1 个答案:

答案 0 :(得分:0)

我认为在cronjob中运行shell脚本作为特定用户,你应该在crontab中选择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 cat /var/spool/cron/crontabs/<user>

你可以从spool找到crontab,它位于所有用户的文件

while(HAL_I2C_Master_Transmit(&hi2c3, 252, (uint8_t*) ADCValue[1], 4, 10000) != HAL_OK)