Skip to content

Instantly share code, notes, and snippets.

@cesalazar
Last active March 22, 2022 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cesalazar/9bd640c824ed92b475e04804c9753ebd to your computer and use it in GitHub Desktop.
Save cesalazar/9bd640c824ed92b475e04804c9753ebd to your computer and use it in GitHub Desktop.
Switch the layout of the connected monitors
#!/bin/bash
#
# ╔═════╗ ╔═══╗
# ║ S ║ ║ V ║ Screen Layout Switcher
# ╚═════╝ ║ ║
# ╔═════╗ ╚═══╝ Handle switching the layout of the connected monitors:
# ║ P ║ (S)econdary, (V)ertical, and (P)rimary
# ╚═════╝ Usage: ./switch-screenlayout.sh [1-4]
# Debug options
# set -euxo pipefail
SELECTION=${1}
[[ ! ${SELECTION} ]] && echo "Pass a number from 1 to 4" && exit 1
MONITORS=$(xrandr | grep " connected")
PRIMARY=$(echo "$MONITORS" | grep primary | awk '{print $1}')
SECONDARY=$(echo "$MONITORS" | head -n2 | tail -n1 | awk '{print $1}')
VERTICAL=$(echo "$MONITORS" | tail -n1 | awk '{print $1}')
NAMES=(" " "Small Single" "Double" "Triple" "Big Single")
[[ $(command -v notify-send) ]] \
&& notify-send "Screen layout: ${NAMES[${SELECTION}]}"
LAYOUT1=("--pos 0x0 " "--off " "--off") # Small Single
LAYOUT2=("--pos 0x1331" "--pos 0x131" "--off") # Double
LAYOUT3=("--pos 0x1331" "--pos 0x131" "--pos 1920x0") # Triple
LAYOUT4=("--off " "--pos 0x131" "--off") # Big Single
# Source:
# https://stackoverflow.com/questions/4582137/bash-indirect-array-addressing
declare -n LAYOUT="LAYOUT${SELECTION}"
toggle_monitor() {
local STATE; STATE=${1}
local RES; RES=${2}
[[ "${STATE}" == "--off"* ]] && echo "--off" || echo "--mode ${RES} ${STATE}"
}
xrandr \
--output ${PRIMARY} $(toggle_monitor "${LAYOUT[0]}" 1920x1080) \
--output ${SECONDARY} $(toggle_monitor "${LAYOUT[1]}" 1920x1200) \
--output ${VERTICAL} $(toggle_monitor "${LAYOUT[2]}" 1920x1200) --rotate left
nitrogen --restore
@cesalazar
Copy link
Author

To be used in i3:

bindsym $mod+$alt+1 --release exec --no-startup-id switch-screenlayout.sh 1
bindsym $mod+$alt+2 --release exec --no-startup-id switch-screenlayout.sh 2
bindsym $mod+$alt+3 --release exec --no-startup-id switch-screenlayout.sh 3
bindsym $mod+$alt+4 --release exec --no-startup-id switch-screenlayout.sh 4

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