SH 脚本在控制台中工作,但在 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

当我用suo执行时

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>

相关内容

最新更新