7

I wrote a small shell script configuring attached external displays with xrandr.

# cat /home/didi/bin/monitor_autoswitcher.sh 
#!/bin/bash

xrandr | grep "HDMI1 connected"
if [[ $? == 0 ]]; then
  # is connected
  xrandr --output HDMI1 --right-of LVDS1 --auto
else
  # not connected
  xrandr --output HDMI1 --auto
fi

xrandr | grep "VGA1 connected"
if [[ $? == 0 ]]; then
  # is connected
  xrandr --output VGA1 --right-of LVDS1 --auto
else
  # not connected
  xrandr --output VGA1 --auto
fi

That works. Now I want to have it triggered automatically and found out that this can be done with udev. I tried

udevadm monitor

which, when plugging in an external displays outputs

KERNEL[465828.240250] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)
UDEV  [465828.243549] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)

and when plugging it out

KERNEL[465836.844209] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)
UDEV  [465836.847445] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)

Also good.

Then I added an udev rule:

# cat 40-external-display.rules 
SUBSYSTEM=="drm", ACTION=="change", RUN+="/home/didi/bin/monitor_autoswitcher.sh"

and restarted udev

service udev restart

Unfortunately, still nothing happens when plugging in/out the display. The script monitor_autoswitcher.sh definitely works, because invoking it manually after plugging does what it should.

What's missing?

bougui
  • 3,507
  • 4
  • 22
  • 27
didi_X8
  • 5,018
  • 10
  • 42
  • 46

1 Answers1

8

This looks like pretty much the same thing. The only real difference I see is that the script sets the DISPLAY variable, which may be key.

http://ruedigergad.com/2012/01/28/hotplug-an-external-screen-to-your-laptop-on-linux/

Paul Archer
  • 366
  • 3
  • 4
  • 2
    It was half of what was missing. Also needed: XAUTHORITY env variable, see http://unix.stackexchange.com/questions/14854/xrandr-command-not-exectured-within-shell-command-called-from-udev-rule. I set your answer as correct because it brought me onto the right track. – didi_X8 Mar 18 '13 at 18:13
  • In my case, the XAuthority variable did not work when set to `~/.XAuthority`. Had to set it to `/run/user/1000/gdm/Xauthority` – ElectRocnic Feb 02 '22 at 18:03