如何显示crontab触发的notify-send消息?
test.sh:/ /usr/bin/notify-send "test"
以下工作: bash ~/Documents/test.sh
但是crontab从不显示通知。 为什么?
*/1 * * * * bash ~/Documents/test.sh
要从Cron执行任何GUI相关应用程序,您应该导出一些桌面环境变量。 以下解决方案基于此答案 ,其中提供了更多详细信息。
如何从Ubuntu 16.04,17.10中的crontab
启动任何GUI相关应用程序以及其他与Gnome的Ubuntu发行版
创建一个启动脚本,该脚本将导出桌面环境变量并启动您的应用程序。 我们称之为gui-launcher
。 它的内容应该是( referencs: [1] , [2]和[3] ):
#!/bin/bash -e # NAME: gui-launcher # Check whether the user is logged-in while [ -z "$(pgrep gnome-session -n -U $UID)" ]; do sleep 3; done # Export the current desktop session environment variables export $(xargs -0 -a "/proc/$(pgrep gnome-session -n -U $UID)/environ") # Execute the input command nohup "$@" >/dev/null 2>&1 & exit 0
- 对于其他桌面环境,在此部分中更改
gnome-session
$(pgrep gnome-session -n -U $UID)
,其中包含正在使用的DE的进程名称,例如mate-session
。 这里列出了最多Ubuntu DE的列表。 Lubuntu执行相同的脚本 – 这里 。 该脚本可用于在当前用户的桌面会话中从TTY或SSH会话启动GUI应用程序。 - 使文件可执行:
chmod +x gui-launcher
。 - 该脚本将一直有效,直到用户登录,包括锁定的屏幕。
- 请不要以root用户身份修改和运行脚本。 它可能对系统有害!
然后以这种方式在crontab
中使用它:
*/1 * * * * /full/path/to/gui-launcher "/full/path/to/the-targer-application"
以下是它在Wayland上的Ubuntu 17.10的工作原理:
-
这里介绍了SSH上相同脚本的实现: 如何通过ssh连接到Ubuntu 16.04服务器后在新终端中运行脚本(.sh)文件?
-
这里有更多的解释: 在重启时运行python脚本的Cron作业不起作用 。
cron和普通用户的环境可能不同。
当您在cron中使用任何脚本时,更好地为它们提供完整路径。