User:Fstirlitz/xrandr display switching script

From ArchWiki
#!/bin/bash

# xrandr display switching script
# by felix - email: at yandex.com, m.p.isaev
# public domain

target="$1"
displays=($(xrandr | awk -F'[ ]' '$1 && (NR > 1) { print $1"="$2 }'))

if [[ -z "$target" ]]; then
	for item in "${displays[@]}"; do
		dpname="${item%=*}"
		dpstate="${item#*=}"
		
		if [[ "$dpstate" = connected ]]; then
			if [[ ( -z "$target" ) || ( "$target" == LVDS* ) ]]; then
				target="$dpname"
			else
				echo "cannot unambiguously determine target display" >&2
				exit 1
			fi
		fi
	done
fi

# echo "configuring $target"

cmdline=xrandr
for item in "${displays[@]}"; do
	dpname="${item%=*}"
	dpstate="${item#*=}"
	cmdline="$cmdline --output $dpname"
	if [[ "$dpname" = "$target" ]]; then
		if [ "$dpstate" = disconnected ]; then
			echo "$target is disconnected" >&2
			exit 1
		fi
		cmdline="$cmdline --auto"
	else
		cmdline="$cmdline --off"
	fi
done

$cmdline