bashrc: how to know X window is available or not?

There is a part in my ~/.bashrc, which sets $EDITOR to be gvim. It works fine when I am in X window. However, if I ssh to my workstation (from another workstation) gvim starts to complain "cannot open display".

Therefore I wish to put an if statement in bashrc, that if X window is available then use gvim, otherwise let it be vim.

How could I achieve that?


Solution 1:

One way to do this tests the existence of the DISPLAY environment variable:

if [ "$DISPLAY" ]
then
    EDITOR=gvim
else
    EDITOR=vim
fi

In some cases, DISPLAY will be set even though your gvim won't be able to contact the X server. In those cases, use the RunningX program:

if RunningX
then
    EDITOR=gvim
else
    EDITOR=vim
fi

Solution 2:

The $DISPLAY environment variable should be set to something if you are in X, and unset if you are not connected to a display.

So you could use this:

if [ -n "$DISPLAY" ]; then
    alias vim='gvim'
else
    alias vim='vim'
fi

But there is another solution. It's called ssh X forwarding.

Run

ssh -X yourworkstation

then you can run vim on a machine you are ssh'd into, and it will display on the machine where you are running X.

Solution 3:

Put this into your .bashrc:

if [ -z "${DISPLAY:-}" ]; then
  EDITOR='vim'
else
  EDITOR='gvim'
fi

Solution 4:

While this is not an answer to your question, I thought it maybe useful to point out that if you're sshing from one workstation running X* to another workstation, you actually can use gvim if you setup X forwarding with ssh. The window information will just be sent over the network and gvim will just pop up like it would if run locally.

Add the following in ~/.ssh/config

Host *
   ForwardX11 yes 

Now you'll be able to just run gvim.

If you're workstation of origin is Windows and not running X, you actually CAN startup an X server locally using Cygwin. Once that's setup, you can configure popular ssh clients like PuTTy to do X11 forwardning, and then gvim will pop up in what appears to be a native windows-decorated window.