1

I am having difficulty running the below simple script from crontab:

#!/bin/bash
notify-send "battery.sh working"

The permissions of the file are rwxr-xr-x and its running fine with either of the commands bash battery.sh and sh battery.sh.

In my crontab, I have tried running it with both bash and sh, with absolute as well as local path. My current crontab looks as follows:

* * * * * /home/marpangal/battery.sh
* * * * * sh battery.sh
* * * * * bash battery.sh
* * * * * sh /home/marpangal/battery.sh
* * * * * bash /home/marpangal/battery.sh

However the cron does not execute the script and I get no message from notify-send.

arpanmangal
  • 1,770
  • 1
  • 17
  • 34
  • 1
    Have you tried just adding the path to the file? like so: `* * * * * /home/marpangal/battery.sh`. Also, is your crontab running as your user? Because the group does not have the execute permission o the file. – natronite Mar 02 '18 at 06:59
  • I added the path to the file like `* * * * * /home/marpangal/battery.sh`. I have also provided the execute permissions to all. But still I am not getting any message from notify-send. I am adding the cron with `crontab -e` . – arpanmangal Mar 02 '18 at 07:04
  • 1
    It's most likely that `notify-send` isn't in the minimal `PATH` that cron uses -- see [superuser: "crontab and binaries in /usr/local/bin"](https://superuser.com/questions/784252/crontab-and-binaries-in-usr-local-bin) and [askubuntu: "Why crontab scripts are not working?"](https://askubuntu.com/questions/23009/why-crontab-scripts-are-not-working) for details and other common problems. – Gordon Davisson Mar 02 '18 at 08:13

2 Answers2

0

notify-send needs the DBUS_SESSION_BUS_ADDRESS environment variable in order to communicate with the current desktop session. Since cron runs with an almost empty environment, this variable is not available.

But you can set it directly in your battery.sh script:

export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)
notify-send "Message from cron"

This looks up the process id of your gnome-session and extracts the DBUS_SESSION_BUS_ADDRESS (along with its value) from then gnome-sessions' environment.

Now notify-send is able to display notifications in your desktop session.

Flopp
  • 1,887
  • 14
  • 24
0

Flopps’s answer gives me a -bash: warning: command substitution: ignored null byte in input – so i tried something different:

export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus
notify-send "Message from cron"

i assume this is not as flexible as the original export but it works for me in my user crontab.

p3k
  • 1
  • 1
  • 1