0

This script works fine in user's crontab, but I need run from ROOT crontab, but not work:

#!/bin/sh 
# cron.sh
# Notifies the user of date and time
source /home/user/.bashrc
pid=$(pgrep -u user openbox | head -n 1)
dbus=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$pid/environ | sed 's/DBUS_SESSION_BUS_ADDRESS=//' )
export DBUS_SESSION_BUS_ADDRESS=$dbus
export HOME=/home/user
export DISPLAY=:0
/usr/bin/notify-send 'title' "$(/bin/date)"

The script was found here: crontab script

The script is placed on /home/user/cron.sh with all permissions(777). My root crontab is:

* * * * * /home/user/cron.sh

If I use this script in normal user crontab it works and show the popup text, but not from root crontab. Syslog (/var/log/syslog ) not show errors when crontab trigger.

  • Please elaborate on a number of things: 1) What is not working, is the script not run at all? 2) What is the location and permissions of the script file. 3) What is the crontab line used to run the script. In general, provide as much info as possible, else it's really hard to help. – Artur Meinild Jun 11 '21 at 10:05
  • Could it be that when run from root, it is the root user that receives the notification, and not your other user? You could add this line to verify that the script actually runs: touch /home/user/script-has-run. If the file /home/user/script-has-run exists, then the script has executed. – Artur Meinild Jun 11 '21 at 10:46
  • 1
    AFAIK source is a bashism - in POSIX /bin/sh you should use . /home/user/.bashrc but really you shouldn't be sourcing a .bashrc into a sh shell - if you want features from the user's .bashrc, switch the shebang to #!/bin/bash – steeldriver Jun 11 '21 at 11:03

1 Answers1

2

I'm pretty sure notify-send needs to be run as the user who should receive the notification. Try to replace the last line with this:

su user -c '/usr/bin/notify-send "title" "$(/bin/date)"'

The su user -c command switches user to user and -c passes the following command to the shell.

This statement should switch to the correct user and run the command.

If you want to run the entire script as another user, take a look at this Q&A from Stack Overflow.

Artur Meinild
  • 26,018
  • I don't think su passes trailing arguments to the -c command, does it? Perhaps that needs to be su user -c '/usr/bin/notify-send "title" "$(/bin/date)"'. Regardless, if you're going to run notify-send as user then it would surely make more sense to run the whole thing from user's crontab ... – steeldriver Jun 11 '21 at 12:31
  • I believe you are right. However, I also really can't figure out the OP's usecase, but have tried to help from what I could find elsewhere. – Artur Meinild Jun 11 '21 at 13:24