Tuesday, June 20, 2017

Linux - Switch display from terminal (virtual and emulated) using xrandr

Situation: I had my laptop (running Ubuntu) connected to my TV via an HDMI cable with the display set to TV only. I then unplugged the HDMI cable without switching the display to Internal (using the "Displays" system settings). The display is supposed to switch automatically but on my machine this sometimes fails to happen leaving me with a running X session which I can't see.

However by pressing Ctrl+Alt+F2 (through F6) I am able to switch to a virtual terminal which shows up on the internal screen just fine.

Solution: Use xrandr to switch the display. But this requires two little tricks because xrandr is an X command and it normally fails on virtual terminals.

sleep 5 && xrandr -d :0 --output LVDS1 --auto

and quickly switch to the terminal running X (Ctrl+Alt+F7 on Ubuntu) before the sleep timer runs out.

Explanation: By sleeping for 5 seconds we allow ourselves time to switch to the virtual terminal running X so that when the xrandr command is issued the X Server is awake to receive it.

Since we are running xrandr from the virtual terminal we have to explicitly specify which display to target. The default display is ":0" meaning the first (zero-indexed) display on the local machine (for remote machine its IP address would precede the ':').

Finally --output LVDS1 --auto tells xrandr to switch to the internal display with default settings.

No comments:

Post a Comment