How to detect availability of GUI in Bash/Shell? How to detect availability of GUI in Bash/Shell? shell shell

How to detect availability of GUI in Bash/Shell?


On macOS, there's not a clearly appropriate way to check this from a shell, as such. There's a programmatic way, and we can use an interpreted language to take advantage of that.

Here's a little script that outputs one of three states, Mac GUI, Mac non-GUI, or X11:

#!/bin/bashif [ `uname` = "Darwin" ]then    if which swift >/dev/null && swift <(cat <<"EOF"import Securityvar attrs = SessionAttributeBits(rawValue:0)let result = SessionGetInfo(callerSecuritySession, nil, &attrs)exit((result == 0 && attrs.contains(.sessionHasGraphicAccess)) ? 0 : 1)EOF)    then        echo "Mac GUI session"    elif [ -n "$DISPLAY" ]    then        echo "Mac X11 GUI session"    else        echo "Mac non-GUI session"    fielif [ -n "$DISPLAY" ]then    echo "X11 GUI session"fi

Macs can have an X server installed, in which case DISPLAY is defined. However, I don't know if your Electron app will work properly in that configuration. So, I detected it separately.


Check if DISPLAY is set in the environment. If it is, you have an Xserver running. If not, you don't. Pretty sure that wayland sets it too.


Here is a working example:

if [ x$DISPLAY != x ] ; then  echo "GUI Enabled"else  echo "GUI Disabled"fi

All this does is checks the $DISPLAY variable.