Display switcher with key+P

Hello, I wrote a script for me to switch display with dual screens, with key shorcut. May be useful for you too? Save the script then set a key shorcut:
Control Center > Keyboard shortcuts > Add > select the script and the key.

Replace the displays labels by yours (DP-0, HDMI-0...) and with your resolutions.

#!/bin/bash

get_active_monitors()
{
    xrandr | awk '/\ connected/ && /[[:digit:]]x[[:digit:]].*+/{print $1}'
}

# Number of display connected
NumberDisplay=$(xrandr | grep " connected"  | grep "" -c)
if [ $NumberDisplay -lt 2 ]; then
    echo "single monitor: no switch"
    exit 0
fi

DisplayActive=$(get_active_monitors)

echo "Display active : $DisplayActive"

case "$DisplayActive" in
    DP-0) notify-send "Clone"
        xrandr --output DP-0 --mode 1366x768 --output HDMI-0 --mode 1366x768 --rate 60 ;;
    HDMI-0) xrandr --output DP-0 --mode 1366x768 --output HDMI-0 --off
        notify-send "Monitor" ;;
    *) notify-send "TV"
        xrandr --output HDMI-0 --mode 1920x1080
        sleep 3s
        xrandr --output DP-0 --off ;;
esac

exit 0
2 Likes

This works for me:

#!/bin/bash
# switchdisplay - Sequentially activate the next single display

displaylines=$(xrandr |grep " connected")
ndisplays=$(grep -c $'\n' <<<"$displaylines")

# If there are no multiple connected display: no action
((ndisplays<2)) && exit 0

displaysoff=$(grep '^[^ ]* connected (' <<<"$displaylines" |grep -o '^[^ ]*')
ndisplaysoff=$(grep -c $'\n' <<<"$displaysoff")
displays=$(grep -o '^[^ ]*' <<<"$displaylines")

next=0 activate= first=
if ((ndisplays-ndisplaysoff==1))
then # If only 1 display is on, activate the next ("normal" case)
  active=$(grep '^[^ ]* connected [^(]' <<<"$displaylines" |grep -o '^[^ ]*')
  for display in $displays
  do
    [[ $first ]] || first=$display
    if [[ $display = $active ]]
    then next=1
    else ((next)) && activate=$display && break
    fi
  done
  [[ $activate ]] || activate=$first
else # Otherwise, just activate the first to start "normal"
  activate=$(head -1 <<<"$displays")
fi

cmd=xrandr
for display in $displays
do
  [[ $display = $activate ]] &&
    cmd+=" --output $display --auto" ||
    cmd+=" --output $display --off"
done
$cmd

exit 0
1 Like