How do I automatically set the $DISPLAY variable for my current session?

user130334 picture user130334 · Jun 29, 2009 · Viewed 109.7k times · Source

I see that $DISPLAY is set to localhost:0.0 if I am running over a vnc server this may not be correct, is there a way to automatically set it in my login script?

Answer

Nick picture Nick · Jul 22, 2009

Here's something I've just knocked up. It inspects the environment of the last-launched "gnome-session" process (DISPLAY is set correctly when VNC launches a session/window manager). Replace "gnome-session" with the name of whatever process your VNC server launches on startup.

PID=`pgrep -n -u $USER gnome-session`
if [ -n "$PID" ]; then
    export DISPLAY=`awk 'BEGIN{FS="="; RS="\0"}  $1=="DISPLAY" {print $2; exit}' /proc/$PID/environ`
    echo "DISPLAY set to $DISPLAY"
else
    echo "Could not set DISPLAY"
fi
unset PID

You should just be able to drop that in your .bashrc file.