Skip to content

Instantly share code, notes, and snippets.

@FlyingFathead
Last active April 18, 2023 12:08
Show Gist options
  • Save FlyingFathead/7b81cb90462eb310240d114796d2b8fa to your computer and use it in GitHub Desktop.
Save FlyingFathead/7b81cb90462eb310240d114796d2b8fa to your computer and use it in GitHub Desktop.
set_primary_display.sh -- a bash script to set your primary display inside a Linux desktop environment using the terminal
#!/bin/bash
# print a terminal-wide horizontal line with '-' characters
function hr_prn(){
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
}
# Get the list of connected displays and their resolutions
DISPLAYS=($(xrandr | grep " connected" | awk '{print $1}'))
CURRENT_PRIMARY=$(xrandr --query | grep " connected primary" | awk '{print $1}')
# Get the list of resolutions for each display
for i in ${!DISPLAYS[@]}; do
RESOLUTIONS[$i]=$(xrandr | grep "${DISPLAYS[$i]}" | awk '{print $4}')
done
# Print the list of displays and their current status
hr_prn &&
echo "::: Available displays:" &&
hr_prn &&
for i in ${!DISPLAYS[@]}; do
if [[ ${DISPLAYS[$i]} == $CURRENT_PRIMARY ]]; then
echo "$i. ${DISPLAYS[$i]} (${RESOLUTIONS[$i]}) *"
else
echo "$i. ${DISPLAYS[$i]} ${RESOLUTIONS[$i]})"
fi
done
# If command line argument is given, use that as choice
if [[ $# -eq 1 ]]; then
CHOICE=$1
else
# Ask the user to choose a display to set as the primary display
hr_prn &&
echo "::: [* = Current main display]"
hr_prn &&
read -p "Enter the number of the display to set as primary: " CHOICE
fi
# Check if the display number exists
if [[ $CHOICE -ge 0 && $CHOICE -lt ${#DISPLAYS[@]} ]]; then
# Check if the display is already the main display
if [[ ${DISPLAYS[$CHOICE]} == $CURRENT_PRIMARY ]]; then
hr_prn &&
echo "::: [ERROR!] Display ${DISPLAYS[$CHOICE]} is already the primary display!" &&
hr_prn
else
# Set the chosen display as the primary display
xrandr --output ${DISPLAYS[$CHOICE]} --primary
hr_prn &&
echo "::: Display ${DISPLAYS[$CHOICE]} set as primary display." &&
hr_prn
fi
else
hr_prn &&
echo "::: [ERROR!] Invalid display number. Please choose a valid number from the list."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment