Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Created January 29, 2022 13:26
Show Gist options
  • Save pythonhacker/b5b4350b18f2d34ae7bdf933ff0a4381 to your computer and use it in GitHub Desktop.
Save pythonhacker/b5b4350b18f2d34ae7bdf933ff0a4381 to your computer and use it in GitHub Desktop.
Toggle Laptop and Monitor Display automatically
#!/bin/bash
# Use this script if you have an external monitor (HDMI) and want that as primary display
# but switch to the laptop monitor (eDP) when the external monitor is off (power off or otherwise)
# Guess if you have the external monitor attached to a UPS device, you don't need this script...!
# Detect when monitor is powered off and switch the laptop display back on
# and vice-versa, keeping the external monitor as primary display whenever
# possible.
function get_laptop_display() {
# Should work for most laptops - if it doesn't
# check the output of `xrandr -q` and get the
# correct string instead of "edp"
xrandr -q | grep -i edp | awk '{print $1}'
}
function get_hdmi_display() {
# Should work for most HDMI monitors - if it doesn't
# check the output of `xrandr -q` and get the
# correct string instead of "hdmi"
xrandr -q | grep -i hdmi | awk '{print $1}'
}
function toggle_edp_on() {
xrandr --output $1 --auto
}
function toggle_edp_off() {
xrandr --output $1 --off
}
function toggle_displays() {
# Detect if HDMI (external monitor) goes off and then
# switch back to laptop display and vice-verza.
display_name=$1
result=`sudo ddcutil getvcp d6 --terse 2>/dev/null| awk '{print $NF}'`
# echo "Result => $result"
case $result in
"x05"|"ERR"|"") toggle_edp_on $display_name ;; # Monitor is off. Power on laptop display
"x01") toggle_edp_off $display_name ;; # Monitor is on. Power off laptop display
esac
}
display_name=`get_laptop_display`
# Run in background
while true
do
toggle_displays $display_name
sleep 2
done&
@pythonhacker
Copy link
Author

Required software - ddcutil

$ sudo apt install ddcutil -y

@polyglothacker
Copy link

polyglothacker commented Jan 29, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment