Possible to run a script when something plugged in / disconnected from Mini DisplayPort?

In /etc/acpi/ there are several scripts that can be customized to do something when a particular event happens on your physical computer, like the lid.sh script which is called when the laptop lid is opened or closed, but I'm looking for a way to detect when something is plugged into or disconnected from the Mini DisplayPort, so that I can run a command.

I don't see any such script in there (unless I've missed something).

The command would be to configure the multi-monitor setup automatically using xrandr. This used to happen automatically in Gnome (using ~/.config/monitors.xml I believe) but I've now switched to xmonad completely and it doesn't automatically detect this.


Yes it should be possible using udev.

I have asked/answered here a similar question (change sound output on HDMI (dis)connect). First you will need to create a udev rule like this:

SUBSYSTEM=="drm", ACTION=="change", RUN+="/usr/local/bin/update_screen_config"

It should be on the same location as in my answer but you can change the name. To know exactly which SUBSYSTEM and ACTION you need use udevadm and connect your DP. In my system, connecting the HDMI screen I get:

$ udevadm monitor
monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent
(here I connected my screen)
KERNEL[16383.092226] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)
UDEV  [16383.281930] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)
(disconnected my screen)
KERNEL[16389.092226] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)
UDEV  [16389.281930] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)

The second part is the creation of /usr/local/bin/update_screen_config (you can give it other name or location). I have used a Python script but you can use anything you want, since it can be executed. This will be the script that is called when the cable is connected/disconnected, so it must find the current state and use xrandr to do what you need. See how I made the detection of the state of the screen and if it suits your needs.

Note: this script is executed as root by udev, so test it as a normal user before you put him on udev.