User Tools

Site Tools


displayvar

Conditionally setting the DISPLAY variable

In OS X, if you want to use X11 programs from the Terminal, you have to set the environment variable DISPLAY as follows:

export DISPLAY=:0.0

You can either put this line in your ~/.bashrc or ~/.profile file, such that the variable is always set. This is useful if you have X11 configured to be started automatically with OS X.

On the other hand, if you only sporadically use X11, the above solution might become a nuisance, especially with programs that try to access an X server, even if they don't actually put any output there (such as Vim). In that case, you can set the variable manually each time you use a program that needs X11.

In the following we show a third, more elegant solution. It is a short script that detects whether X11 is running, and only then sets the variable.

Put the following code in your ~/.bashrc or ~/.profile file:

PSOUT=`ps auxw | grep '/Applications/Utilities/X11.app/Contents/MacOS/X11' | grep -v grep`

if [ -n "$PSOUT" ]; then
  # X11 is running
  export DISPLAY=":0.0"
fi

This code checks the list of running processes for an instance of X11 by grepping the output of ps, and only sets the variable if the result is a non-zero-length string.

displayvar.txt · Last modified: 2008/02/12 13:53 by kleiner