Send desktop notifications with notify-send to other users from a cron script

One can use the command

notify-send "title" "body"

to send a notification to the desktop-environment which displays a nice message. You just need libnotify-bin installed and together with dbus a user can issue notifications to its desktop-environment.

I have a shell script which is executed via cron that needs to send messages/notifications to a specific user when it starts and when it finishes doing stuff. That script is executed via cron by the root-user.

Via sudo one can execute that command as/for another user. But running

sudo -u xxx notifiy-send foo bar

via cron does not send messages to my desktop, yet the message shows if run manually. The reason is cron does not know about dbus-stuff and thus cannot connect to the desired users dbus-socket. Cron is missing all the environment variables each real user has. One of the important env variable is the DBUS-ADDRESS. We must ensure that the dbus socket for each user we want to send messages to is known to cron.

So instead of simply running notify-send via cron we additionally have to determine the dbus-sockets-addresses in use for the targeted user…

Here is an example:

# needed for notify-send notification from root executed via cron
DBUS_ADDRESS=`grep "DBUS_SESSION_BUS_ADDRESS=" /home/croessler/.dbus/session-bus/*-0 | cut -d "=" -f 2-`
DISPLAY=:0

sudo -u croessler DISPLAY=${DISPLAY} DBUS_SESSION_BUS_ADDRESS=${DBUS_ADDRESS}  notify-send "WorkstationBackup" "Beginning Backup now..."
...
...
sudo -u croessler DISPLAY=${DISPLAY} DBUS_SESSION_BUS_ADDRESS=${DBUS_ADDRESS}  notify-send "WorkstationBackup" "Backup is done."

We determine the dbus-address by grep’ing the dbus-socket-files in the desired users home-folder, then use that to pass it as variable to the notify-send command.

Not sure if there is a better way to fetch a users dbus-address so i took the grep-cut way of doing things.