How to list active displays (on command line)?

xrandr -q gives me a list of connected displays, but how can I find out (script friendly) if a display is currently active?

Context: I would like to write a script to toggle a Display. If it's active it should be turned off, if it isn't it should be turned on.

Note: xrandr -q basically provides this information since active modes are marked with a *, but this information is hard to extract within a bash script.


Solution 1:

The displays that are active have their resolution and offset number shown in the identifying line of xrandr output. Here's what I mean:

$ xrandr | grep connected                                    
eDP1 connected primary 1366x768+1280+256 (normal left inverted right x axis y axis) 345mm x 194mm
DP1 disconnected (normal left inverted right x axis y axis)
HDMI1 disconnected (normal left inverted right x axis y axis)
VGA1 connected 1280x1024+0+0 (normal left inverted right x axis y axis) 340mm x 270mm
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

In the output you can see that my laptop's built-in monitor and VGA1 both are connected, and have resolution ( in case of built-in display eDP1 it is 1366x768 ). Thus the task simply becomes text-processing of the output. For that purpose , I've written a small function that you can use in your scripts or ~/.bashrc:

get_active_monitors()
{
    xrandr | awk '/\ connected/ && /[[:digit:]]x[[:digit:]].*+/{print $1}'
}

Here's test runs:

With VGA monitor on

enter image description here

With VGA monitor off

enter image description here