Bash – Detecting X Session in a Bash Script

bashenvironment-variablesxorg

Recently I put xset b off to my .bashrc. Now I'm annoyed by the error thet pops up when I log in via tty or via ssh, i.e. outside X session.

First thing that came in my mind was [[ -z "$SOME_VAR" ]] && xset b off (well, turns out that testing variable being set vs. being empty is a different question). But which SOME_VAR is the correct one?

So I diffed tty's set output and urxvt's set output to see which variables are set in X and missing in tty. As expected, there were quite many differences (listing only those that seemed relevant to me):

  • DESKTOP_SESSION
  • DISPLAY
  • GDMSESSION
  • SESSION_MANAGER
  • WINDOWID
  • WINDOWPATH
  • XAUTHORITY
  • XDG_SESSION_COOKIE
  • XDG_CONFIG_DIRS
  • XDG_DATA_DIRS
  • XDG_MENU_PREFIX

Which one is the most correct and universal one to test in order to detect if I'm in an X session or not? Something that would work across as many distros and platforms and desktop environments as possible?

Or is there even better way than testing environment variables?

Best Answer

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

Related Question