Automatically detect when HDMI is plugged in

14,669

I am using two different ways to determine if HDMI is plugged in:

a) Using xrandr
A simple xrandr will report your hdmi monitor as connected To use this in a script you can do something like:

hdmi_active=$(xrandr |grep ' connected' |grep 'HDMI' |awk '{print $1}')

Above will return the connected hdmi port (i.e HDMI-1) or will return nothing if no HDMI is connected.

You can then use something like

[[ ! -z "$hdmi_active" ]] && do_your_stuff 

z becomes true if $hdmi_active is not set . ! z reverts this behavior and returns true if hdmi_active has a value = hdmi is connected

b) Using the HDMI status file:

$ cat /sys/class/drm/card0/*HDMI*/status

This returns connected / disconnected for your hdmi ports:

$ cat /sys/class/drm/card0/*HDMI*/status
disconnected
disconnected

You can then test against that result with something like:

hdmi_active="$(cat /sys/class/drm/card0/*HDMI*/status |grep '^connected')" #Using ^ we avoind matching disconnected from the regex match, since ^ in an anchor to the beginning of the line
[[ ! -z "$hdmi_active" ]] && do_your_stuff #hdmi is active
Share:
14,669
Katembers
Author by

Katembers

Updated on August 01, 2022

Comments

  • Katembers
    Katembers over 1 year

    Sometimes I connect my laptop to my TV over HDMI to have a bigger screen. Unfortunately, it doesn't automatically switch the audio output, so I have to do that myself every single time I plug or unplug it, with either of those two, to have the sound come from where I want it to come from.

    • pacmd set-card-profile 0 output:hdmi-stereo-extra1
    • pacmd set-card-profile 0 output:analog-stereo+input:analog-stereo

    Is there any way to detect if HDMI is plugged in, or at least if a change has occurred? Thanks!

    Linux Mint 18.2 Xfce x64, Asus P756U

  • nagy.zsolt.hun
    nagy.zsolt.hun almost 3 years
    What is the status if the HDMI cable is plugged in to the laptop, but on the screen/TV another HDMI input is selected? I'm wondering if I can detect input change on the screen.
  • Juanse Cora
    Juanse Cora over 2 years
    I tell you know. It does not work, and as of now, it is an unsolved problem.
  • George Vasiliou
    George Vasiliou over 2 years
    @JuanseCora When you say "it does not work" you refer to my solution or to the question posted by nagy.zsolt.hun ?
  • Juanse Cora
    Juanse Cora over 2 years
    @GeorgeVasiliou I refer to nagy.zsolt.hun comment in which he asks if it can detect input change on the scrren.