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

# List local displays

# X sockets directory

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;
    # root - show display, process name and process id
    for line in `lsof "$file" | awk 'NR>1 {print $1 "/" $2}'`; do
      echo $display $line

Sample output

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


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.