Shell script with export command and notify-send via crontab not working. Exported variable is set by a command

StackOverflow https://stackoverflow.com/questions/23415117

  •  13-07-2023
  •  | 
  •  

Question

I'd like to send a notification bubble to the gnome desktop from a shell script that is executed by cron.

To make it able to communicate with the desktop environment DBUS_SESSION_BUS_ADDRESS env variable needs to be set within the script. I'm trying to achieve this by the following code which isn't working.

#!/usr/bin/env sh
export DISPLAY=:0
dbus=$(env | grep DBUS_SESSION_BUS_ADDRESS | sed 's/DBUS_SESSION_BUS_ADDRESS=//')
export DBUS_SESSION_BUS_ADDRESS=$dbus
[...]
notify-send -u critical "Blah" "Blubb"

When hardcoded it works fine

export DBUS_SESSION_BUS_ADDRESS='unix:abstract=/tmp/dbus-HjnsLUTTrn,guid=17c8962443279ebbe24dcd66536278dd'

Problem is, the dbus session address changes so hardcoding isn't an option.

What am I doing wrong?

Was it helpful?

Solution

env when invoked from a script run by cron, only had the following variables set in my box.

SHELL=/bin/sh USER=clement PATH=/usr/bin:/bin PWD=/home/clement HOME=/home/clement SHLVL=2 LOGNAME=clement _=/usr/bin/env

and so grep in

$(env | grep DBUS_SESSION_BUS_ADDRESS | sed 's/DBUS_SESSION_BUS_ADDRESS=//')

didn't give any output. The following should work.

#!/bin/bash
PID=$(pgrep gnome-session)
dbus=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-)
export DBUS_SESSION_BUS_ADDRESS=$dbus
notify-send -u critical "Blah" "Blubb"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top