2

On my system, notify-send requires 3 enviorment variables to run, which are kept in a file which is generated automatically on logon:

/home/anmol/.env_vars:

DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-PwezoBTpF3
export DBUS_SESSION_BUS_ADDRESS
XAUTHORITY=/home/anmol/.Xauthority
export XAUTHORITY
DISPLAY=:0
export DISPLAY

And, in the crontab buffer, I have entered this:

PATH=/home/anmol/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

* * * * *  /home/anmol/display-notif.sh

where display-notif.sh contains:

#!/usr/bin/env bash

. /home/anmol/.env_vars
notify-send 'hello'

Although I am able to run notify-send from non-sudo cron (crontab -e) through this setup, I am unable to do so from sudo cron (sudo crontab -e).

I also tried checking if there are any errors being generated:

* * * * *  /home/anmol/display-notif.sh 2>/home/anmol/log

But that log file is empty.

How do I make it work from sudo cron ?

I am using Ubuntu 16.04.

6
  • What are you trying to do? Why would you want to use sudo here? is root running their own X session? If not, if you just want to connect to your own X session, sudo is not needed. Also, note that you don't need to declare the variables and export them later, you could just write export DISPLAY=:0.
    – terdon
    Jun 12, 2016 at 14:45
  • @terdon I'm doing this because I'm actually running some other command from root crontab, and I want to display notification whenever that command runs. Jun 12, 2016 at 14:47
  • OK. Does it work if you run xhost + from your normal user's session before the root crontab runs?
    – terdon
    Jun 12, 2016 at 14:51
  • No. It does not. Jun 12, 2016 at 16:07
  • Is your home directory encrypted, or more precisely, what filesystem type is your home directory on? Try running the script from a root prompt in a terminal, it may be easier to see error messages. Jun 12, 2016 at 20:31

2 Answers 2

3

This function ( from https://unix.stackexchange.com/a/344377/7286 ) works for me in Ubuntu 16.04 :

notify_all() {
    local title=$1
    local msg=$2

    who | awk '{print $1, $NF}' | tr -d "()" |
    while read u d; do
        id=$(id -u $u)
        . /run/user/$id/dbus-session
        export DBUS_SESSION_BUS_ADDRESS
        export DISPLAY=$d
        su $u -c "/usr/bin/notify-send '$title' '$msg'"
    done 
}
1
  • /run/user/$id/dbus-session no longer exists, so this no longer works.
    – hackerb9
    Jun 8 at 0:17
0

It is working after replacing

* * * * *  /home/anmol/display-notif.sh

with

* * * * *  sudo -u anmol /home/anmol/display-notif.sh
1
  • This negates the requirement to run the job as root, by having it run as the original user. At this point you might as well have not run it as root in the first place
    – roaima
    May 8, 2021 at 7:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .