首页 文章

从crontab运行bash脚本

提问于
浏览
1

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

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

该文件的权限是 rwxr-xr-x ,并且使用 bash battery.shsh battery.sh 命令运行正常 .

在我的crontab中,我尝试使用 bashsh 运行它,具有绝对路径和本地路径 . 我目前的crontab如下所示:

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

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

2 回答

  • 0

    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 能够在桌面会话中显示通知 .

  • 0

    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中适用于我 .

相关问题