switching

BASH Script for Switching Between HDMI and Laptop Screen

Handy bash script I wrote, or actually adapted, for switching between your HDMI monitor and your laptop screen — you just run this when you log-in (also opens or closes gkrellm, which doesn’t fit on the tiny laptop screen) …

#!/bin/bash

# roughly based on:
# http://unix.stackexchange.com/questions/4489/a-tool-for-automatically-applying-randr-configuration-when-external-display-is-p

# laptop screen is LVDS1
# 1080p large-screen is HDMI1

# default monitor is LVDS1
MONITOR=LVDS1

# functions to switch from LVDS1 to HDMI and vice versa,
# give 5 seconds to detect modelines for HDMI monitor or fails
# as it takes a little while for modelines to be auto detected
function ActivateHDMI {
echo "Switching to 1080p monitor, HDMI1 in 5 seconds ..."
sleep 5;
xrandr --output HDMI1 --auto --output HDMI1 --primary --output LVDS1 --off
gkrellm -g -0+25 &
MONITOR=HDMI1
}
function DeactivateHDMI {
echo "Switching to laptop screen, LVDS1 now ..."
killall gkrellm
xrandr --output LVDS1 --auto --output LVDS1 --primary --output HDMI1 --off
MONITOR=LVDS1
}

# functions to check if HDMI is connected and in use
function HDMIActive {
[ $MONITOR = "HDMI1" ]
}

function HDMIConnected {
! xrandr | grep "^HDMI1" | grep disconnected
}

# every one 1 second
# poll to see if HDMI1 is connected

while true
do
if ! HDMIActive && HDMIConnected
then
ActivateHDMI
fi

if HDMIActive && ! HDMIConnected
then
DeactivateHDMI
fi

sleep 1s
done