How do I programmatically test if it's possible to connect to the X server specified in $DISPLAY

You can try with the xset command :

if [[ ! $(xset -q) ]]; then
   # the X server is not reachable
else
   # the X server is reachable
fi

I am guessing there is a better solution. But you can always just use a small tool like xclock and check the exit status.

if [[ ! xclock ]]; then
  exit 1
fi
pkill xclock

But man, that is ugly :-)

Less Hacky, put the following in checkX.c:

#include <X11/Xlib.h>
#include <stdio.h>

int main() 
{
    Display *display;
    if( ! (display=XOpenDisplay(NULL) ) ) {
        return(1);
    }
    return 0;
}

Then:

gcc -lX11 checkX.c -o checkX
chmod +x checkX

Lastly:

if ./checkX; then
   echo "We are good to go!"
fi

Heres a possible WayToDoIt, not sure how good it is though.

  x_works(){
     # If there is no xdpyinfo
     # Bash will return 127
     # If X cant connect, it returns 1
     # If X can connect, it returns 0
     xdpyinfo 1>/dev/null 2>&1
     WORKS="$?"
     return $WORKS
  }

  if x_works; then 
   ...

This appears to be working.