Detecting X session in a bash script (.bashrc etc.)

I think checking DISPLAY would be the best approach.

  • It handles remote logins (e.g. ssh -X).
  • It is available in most - if not all - platforms.
  • It is independent of window manager/DE.

A simple and effective way to test that your display server is available and valid is to test it with xhost. You can't always rely on checking for a value in the DISPLAY variable since it could be set with an invalid value.

if xhost >& /dev/null ; then echo "Display exists"
else echo "Display invalid" ; fi

The reason I do this is because I run several scripts in my user crontab that operate on the display when it exists, but work differently when not. At the top of my crontab, I set the DISPLAY variable to :0 even though it doesn't exist yet. Scripts in the crontab that start with @reboot will start regardless of whether you have a display or not. This will allow you to dynamically detect when your display comes and goes within the same script.

NOTE: The >& only works in bash >= 4. Otherwise use > /dev/null 2>&1


I usually use the TERM variable to test for X in my scripts.

TERM is usually set to linux on TTY and xterm on X.
I use the word "usually" here, since applications like GNU Screen and TMux seem to mess with the TERM Variable.