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


export DISPLAY

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


* * * * *  /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.

  • 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 '16 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. – Anmol Singh Jaggi Jun 12 '16 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 '16 at 14:51
  • No. It does not. – Anmol Singh Jaggi Jun 12 '16 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. – Gilles 'SO- stop being evil' Jun 12 '16 at 20:31

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 DISPLAY=$d
        su $u -c "/usr/bin/notify-send '$title' '$msg'"
| improve this answer | |

It is working after replacing

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


* * * * *  sudo -u anmol /home/anmol/display-notif.sh
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.