How to Detect Desktop Environment in a Bash Script

bashbash-scriptdesktop-environment

I am writing a bash script that needs to know which desktop environment (XFCE, Unity, KDE, LXDE, Mate, Cinnamon, GNOME2, GNOME3,… ) is running.

How can I obtain that information?

Best Answer

The main problem with checking the DESKTOP_SESSION is that it is set by the display manager rather than the desktop session and is subject to inconsistencies. For lightdm on Debian, the values come from the names of files under /usr/share/xsessions/. DESKTOP_SESSION reflects the desktop environment if a specific selection is made at log in, however the lightdm-xsession is always used the default session.

GDMSESSION is another option, but seems to have a similar predicament (it is the same value as DESKTOP_SESSION for me).

XDG_CURRENT_DESKTOP looks like a good choice, however it is currently not in the XDG standard and thus not always implemented. See here for a discussion of this. This answer shows its values for different distros/desktops, I can also confirm it is currently not available for me on XFCE.

The reasonable fallback for XDG_CURRENT_DESKTOP not existing would be to try XDG_DATA_DIRS. Provided the data files for the desktop environment are installed in a directory bearing its name, this approach should work. This will hopefully be the case for all distros/desktops!

The following (with GNU grep) tests for XFCE, KDE and Gnome:

echo "$XDG_DATA_DIRS" | grep -Eo 'xfce|kde|gnome'

POSIX compatible:

echo "$XDG_DATA_DIRS" | sed 's/.*\(xfce\|kde\|gnome\).*/\1/'

To combine with checking XDG_CURRENT_DESKTOP:

if [ "$XDG_CURRENT_DESKTOP" = "" ]
then
  desktop=$(echo "$XDG_DATA_DIRS" | sed 's/.*\(xfce\|kde\|gnome\).*/\1/')
else
  desktop=$XDG_CURRENT_DESKTOP
fi

desktop=${desktop,,}  # convert to lower case
echo "$desktop"
Related Question