【问题标题】:Running bash script from crontab从 crontab 运行 bash 脚本
【发布时间】:2018-08-10 09:00:09
【问题描述】:

我无法从 crontab 运行以下简单脚本:

#!/bin/bash
notify-send "battery.sh working"

该文件的权限为rwxr-xr-x,使用bash battery.sh 和sh battery.sh 中的任何一个命令都可以正常运行。

在我的 crontab 中,我尝试使用 bash 和 sh 运行它,使用绝对路径和本地路径。我当前的 crontab 如下所示:

* * * * * /home/marpangal/battery.sh
* * * * * sh battery.sh
* * * * * bash battery.sh
* * * * * sh /home/marpangal/battery.sh
* * * * * bash /home/marpangal/battery.sh

但是 cron 不执行脚本,并且我没有收到来自 notify-send 的消息。

【问题讨论】:

  • 您是否尝试过仅添加文件路径?像这样:* * * * * /home/marpangal/battery.sh。另外,您的 crontab 是否以您的用户身份运行?因为该组没有文件的执行权限。
  • 我添加了文件的路径,例如* * * * * /home/marpangal/battery.sh。我还为所有人提供了执行权限。但我仍然没有收到来自通知发送的任何消息。我正在使用 crontab -e 添加 cron。
  • notify-send 很可能不在 cron 使用的最小 PATH 中——有关详细信息和其他常见问题,请参阅 superuser: "crontab and binaries in /usr/local/bin" 和 askubuntu: "Why crontab scripts are not working?"。

标签: bash ubuntu cron notify-send


【解决方案1】:

notify-send 需要DBUS_SESSION_BUS_ADDRESS 环境变量才能与当前桌面会话通信。由于cron 在几乎为空的环境中运行,因此该变量不可用。

但是你可以直接在你的battery.sh脚本中设置:

export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)
notify-send "Message from cron"

这会查找 gnome-session 的进程 ID,并从 gnome-sessions' 环境中提取 DBUS_SESSION_BUS_ADDRESS(及其值)。

现在notify-send 能够在您的桌面会话中显示通知。

【讨论】:

    【解决方案2】:

    Flopps 的回答给了我一个-bash: warning: command substitution: ignored null byte in input——所以我尝试了一些不同的东西:

    export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus
    notify-send "Message from cron"
    

    我认为这不像原始导出那样灵活,但它适用于我的用户 crontab。

    【讨论】:

      猜你喜欢
      • 2017-12-02
      • 1970-01-01
      • 2016-10-20
      • 2014-02-20
      • 2022-01-05
      • 2017-12-12
      • 2017-11-20
      • 1970-01-01
      相关资源
      最近更新 更多