How to list local displays

I was always curious about how to list local displays as it is quite interesting issue. Solution is not immediately apparent, but easy enough to spot after a while as it does not require anything more than little observations.

Shell script

#!/bin/sh
# List local displays

# X sockets directory
directory="/tmp/.X11-unix"

for file in ${directory}/*; do
  # translate file to display
  display=`echo "$file" | sed -e "s|${directory}/X|:|"`

  if [ "$(id -u)" -ne "0" ]; then
    # not root - show display
    echo $display;
  else
    # root - show display, process name and process id
    for line in `lsof "$file" | awk 'NR>1 {print $1 "/" $2}'`; do
      echo $display $line
    done
  fi
done

Sample output

$ sh list_displays.sh 
:0
:1
:11
:33
$ sudo sh list_displays.sh 
[sudo] password for milosz: 
:0 kdm/3579
:0 Xorg/3610
:1 Xephyr/22194
:11 Xephyr/22883
:33 Xephyr/22949

Notes

Main idea used in the above shell script is very simple as you do not need anything more then basic utilities - check out /tmp/.X11-unix directory and use lsof command to get more information.