繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM