notify-send 命令不会通过 systemd 服务启动通知

notify-send command doesn't launch the notification through systemd service

我正在尝试使用 systemd 服务通过 .sh 脚本和 notify-send 命令发送桌面通知。我的脚本 notif.sh 如下:

#!/bin/bash
notify-send "Hello World"

我的 systemd 服务 notifme.service 是下一个:

[Unit]
Description=should launch a desktop notification

[Service]
User=user
Type=simple
ExecStart=/bin/bash /home/user/notif.sh
Environment="DISPLAY=:0" "XAUTHORITY=/home/user/.Xauthority"

当我启动该服务时,除了不显示通知外,一切似乎都运行良好。当我手动 运行 脚本时,通知脚本正常工作。 当我 运行 systemctl status notifme.service 输出是:

● notifme.service - should launch a desktop notification
     Loaded: loaded (/etc/systemd/system/notifme.service; disabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-02-13 14:39:00 CET; 39s ago
   Main PID: 15771 (bash)
      Tasks: 9 (limit: 18678)
     Memory: 3.5M
     CGroup: /system.slice/notifme.service
             ├─15771 /bin/bash /home/user/notif.sh
             ├─15773 notify-send Hello World
             ├─15780 dbus-launch --autolaunch=017e96ffe51b466384d899f21cbecdc5 --binary-syntax --close-stderr
             ├─15781 /usr/bin/dbus-daemon --syslog-only --fork --print-pid 5 --print-address 7 --session
             ├─15783 /usr/bin/dbus-daemon --syslog-only --fork --print-pid 5 --print-address 7 --session
             └─15784 /usr/bin/plasma_waitforname org.freedesktop.Notifications

feb 13 14:39:00 slimbook systemd[1]: Started should launch a desktop notification.
feb 13 14:39:00 slimbook dbus-daemon[15781]: [session uid=1000 pid=15779] AppArmor D-Bus mediation is enabled
feb 13 14:39:00 slimbook dbus-daemon[15781]: [session uid=1000 pid=15779] Activating service name='org.freedesktop.Notifications' requested by ':1.0' (uid=1000 pid=15773 comm="notify-send Hello World " label="unconfined")

有谁知道为什么没有显示通知?提前致谢

问过同事后,当脚本从服务中 运行 时,似乎 DBUS_SESSION_BUS_ADDRESS 变量不可用。只需在脚本中添加 export 命令就足够了:

#!/bin/bash
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=/run/user/${UID}/bus}"
notify-send "Hello World"

显然,在服务文件中,Environment是不必要的。