【问题标题】:Cron job doesn't execute the shell scriptCron 作业不执行 shell 脚本
【发布时间】:2018-09-25 22:59:44
【问题描述】:

我想创建一个 shell 脚本,它将由 cron 作业每分钟运行一次。脚本的工作是在不同的情况下通知我(拔下)充电器:

  1. 当电池处于充电状态且电量约为 80% 时,它会提醒我拔掉数据线。

  2. 当电池处于放电状态且电量约为 40% 时,它会提醒我将电缆插回。

我的 crontab 文件:

SHELL=/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

* * * * * /home/aleksa/charge.sh
# newline 

我的/home/aleksa/charge.sh 脚本:

#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

RESPONSE="$(upower -i /org/freedesktop/UPower/devices/battery_BAT0)"

#if percentage is around 40%, and state is discharging
if echo "${RESPONSE}" | grep -E '38%|39%|40%|41%|42%' && echo "${RESPONSE}" | grep -w 'discharging'
then zenity --notification --window-icon=update.png --text "Connect charger"; 
fi

#if percentage is around 80%, and state is charging
if echo "${RESPONSE}" | grep -E '78%|79%|80%|81%|82%' && echo "${RESPONSE}" | grep -w 'charging'
then zenity --notification --window-icon=update.png --text "Disconnect charger"; 
fi

我认为问题出在脚本中,因为我尝试了不同的方法来检测问题出在哪里:

  1. 脚本在独立于 cron 执行时有效
  2. cron 作业有效 - 我通过每分钟将 date 命令响应附加到文件来测试它
  3. 我试过不声明RESPONSE变量,还是不行

【问题讨论】:

  • 这是您操作系统上的合法crontab 文件吗?此外,这个问题可能是题外话,因为它是关于 crontab 配置的,在 unix.stackexchange.com 上可能更好。
  • @AndrewHenle 是的,它是合法的,我省略了文件的其余部分。并感谢您的反对(如果是你)。
  • 你的脚本可执行吗? crontab 用户是否与具有权限的用户相同? crontab 是否适用于其他事情,例如date>/tmp/proof
  • @PaulHodges '您的脚本可执行文件吗' -> 是的。 'crontab 是否适用于其他事情,例如 date>/tmp/proof? ' -> 确实如此,我写了有问题的细节
  • 有日志吗?

标签: bash shell cron


【解决方案1】:

在调用 Zenity 之前设置您的 $DISPLAY 变量。

export DISPLAY=:0   

Understanding linux DISPLAY variable

【讨论】:

    最近更新 更多