Quickly switch between two custom screen resolutions from the Linux command line

Primarily as a reminder to myself, here’s a small script droppable into ~/bin that allows switching between two custom Linux screen resolutions, that is, resolutions the X server does not necessarily already know about, from the command line.

My use case? A virtual machine within virt-viewer and switch between my laptop’s internal display and an external monitor.

Copy and paste into ~/bin/customres (or whatever you would like to call it), adapt the variables at the top of the script and set up two symlinks lores and hires to it.

#!/bin/bash

OUTPUT="Virtual-1"
LORES_X=1920
LORES_Y=944
HIRES_X=2560
HIRES_Y=1300

function define_mode {
	xres="$1"
	yres="$2"

	gtf_output=$(gtf $xres $yres 60 | sed -n '/Modeline/{s,.*Modeline ,,;s,_[^"]*",",;p}')
	modename=${gtf_output%% *}
	modename=${modename//\"/}
	modedef=${gtf_output#* }
	xrandr --newmode ${modename} ${modedef}
	xrandr --addmode $OUTPUT ${modename}
}

if [ "$(basename $0)" == "lores" ] ; then
	xrandr --output Virtual-1 --mode ${LORES_X}x${LORES_Y} 2>/dev/null || {
		define_mode ${LORES_X} ${LORES_Y}
		xrandr --output Virtual-1 --mode ${LORES_X}x${LORES_Y}
	}
elif [ "$(basename $0)" == "hires" ] ; then
	xrandr --output Virtual-1 --mode ${HIRES_X}x${HIRES_Y} 2>/dev/null || {
		define_mode ${HIRES_X} ${HIRES_Y}
		xrandr --output Virtual-1 --mode ${HIRES_X}x${HIRES_Y}
	}
else
	echo "ERROR: Must run me via either \"lores\" or \"hires\" symlink!"
fi