Vivek Pradhan
Vivek Pradhan

Reputation: 4847

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'

Upvotes: 0

Views: 713

Answers (3)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70792

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'

Upvotes: 2

Gilles Quénot
Gilles Quénot

Reputation: 185073

I suspect an environment problem.

So in your script, put :

#!/bin/bash -x

source ~/.bashrc || source /etc/profile
exec &>/tmp/trace
# rest of the script there

and tell us what's going on.

Edit : Your script should start with :

#!/bin/bash

source ~/.bashrc || source /etc/profile
export DISPLAY=:0
# rest of the script there

Upvotes: 1

tripleee
tripleee

Reputation: 189387

If the program you are running requires X, it cannot run without X. Either somehow authorize it to connect to your X session, or run it from within your X session.

Upvotes: 0

Related Questions