Date Category tech

I move my laptop around a lot, and I’m often connecting to or disconnecting from my external monitor. Switching to this display manually was getting annoying (since Ubuntu apparently broke the Fn+F8 method), so I wrote this:

#!/bin/bash

# In priority order
DISPLAYS="DP-1 LVDS-1"

current=""
while true; do
    prev="$current"
    for display in $DISPLAYS; do
        if [ `cat /sys/class/drm/card0-$display/status` = connected ]; then
            current="$display"
            break
        fi
    done
    if [ "$current" != "$prev" ]; then
        echo "Turning $current on."
        xrandr --output $display --auto
        for display in $DISPLAYS; do
            if [ "$display" != "$current" ]; then
                echo "Turning $display off."
                xrandr --output $display --off
            fi
        done
    fi
    sleep 5
done

It polls every 5 seconds to see which display(s) are connected, and activates the one that has the highest priority (based on the order listed in the DISPLAYS variable). (You can see the names of your outputs by running xrandr.) Now when I plug in my DVI cable, the X output is set to the monitor; when I unplug, the laptop’s LCD takes over again.

I set it to run in the background when I start a new X session. I call it monitor_monitor.