Q:

Bash script not working properly when run automatically

I have a bash script that prints a notification using the notify-OSD only when my laptop is connected to a network. So I have placed the bash script in /etc/network/if-up.d
I printed some log messages into a file to confirm that the script is indeed running. However the notification thing does not seem to work. I just added this line to the file
 notify-send -u 'critical' -i /home/vivek/Downloads/proxy.ico 'SetProxy Status' 'proxy set to auto'

However when i run that script explicitly (by double clicking on it or) from the terminal like this:
cd /etc/network/if-up.d
./setproxy

setproxy is the name of the bash file, then i see the notification working perfectly. Why this behaviour? How can i fix this? I am using ubuntu 12.04
Output in /tmp/trace :
+ nmcli con status
+ grep -q 'Hostel\|IITD'
+ '[' 1 -eq 0 ']'
+ gsettings set org.gnome.system.proxy mode none

** (process:12320): WARNING **: Command line `dbus-launch     --autolaunch=673e71ca3fc5f402403d22380000000a --binary-syntax --close-stderr' exited with non-zero exit status 1: Autolaunch error: X11 initialization failed.\n

** (process:12320): WARNING **: Command line `dbus-launch --autolaunch=673e71ca3fc5f402403d22380000000a --binary-syntax --close-stderr' exited with   non-zero exit status 1: Autolaunch error: X11 initialization failed.\n
+ echo 'You are outside college! No Proxy'
+ notify-send -u critical -i /home/vivek/Downloads/proxy.ico 'SetProxy Status' 'You are outside college, proxy set to none'

A:

If you want to use DISPLAY, you have to set XAUTHORITY too, but that's a little more complicated (depending on username and a random string) try this:
#!/bin/bash

export displayOwner=vivek     # enter your usename here
export DISPLAY=:0
export XAUTHORITY=$(echo /var/run/gdm3/auth-for-${displayOwner}-*/database)

notify-send -u 'critical' -i /home/vivek/Downloads/proxy.ico 'SetProxy Status' 'proxy set to auto'

