Wednesday, September 09, 2015

Use xrandr to center primary below.

I was searching today for a tool that can arrange my dual-screen set-up in Linux such that the primary (laptop) screen is position exactly centre and below the external screen. I know there exist visual tools to do this, but as I'm running i3 wm I like to figure out how to do it from a script using xrandr.

Since I wasn't able to find something that fit my problem exactly, I spent a few minutes figuring out the necessary commands.

Here we go:

#!/bin/bash 
 
# script can be improved by using 'xrandr -q | grep '\'' to find 
# information about laptop-screen (primary) and other screen 
# This only works with two connected 

mainscreen=$(xrandr -q | grep '\' | grep 'primary') 
main_id=$(echo $mainscreen | awk '{print $1}') 
main_x=$(echo $mainscreen | awk '{print $4}' | sed 's/\(.*\)x.*/\1/') 
main_y=$(echo $mainscreen | awk '{print $4}' | sed 's/.*x\([^+]*\).*/\1/') 
 
otherscreen=$(xrandr -q | grep '\' | grep -v 'primary') 
other_id=$(echo $otherscreen | awk '{print $1}') 
other_x=$(echo $otherscreen | awk '{print $3}' | sed 's/\(.*\)x.*/\1/') 
other_y=$(echo $otherscreen | awk '{print $3}' | sed 's/.*x\([^+]*\).*/\1/') 
 
center_left=$(($other_x/2-$main_x/2)) 
 
# use xrandr to center primary screen below  
xrandr --output "$main_id" --pos ${center_left}x${other_y} --output "$other_id" --pos 0x0 

First we detect the primary screen, its ID and dimensions. Then we do the same for the secondary screen. Finally we do a simple calculation in order to figure out the correct position, and run xrandr using the pos argument to position the displays the way we like.

Pretty simple actually!

Take care:)