bash 插入 HDMI 时自动检测

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47960344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:41:39  来源:igfitidea点击:

Automatically detect when HDMI is plugged in

linuxbashaudiohdmi

提问by Katembers

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.

有时我通过 HDMI 将笔记本电脑连接到电视以获得更大的屏幕。不幸的是,它不会自动切换音频输出,所以我每次插入或拔出它时都必须自己这样做,使用这两者中的任何一个,以使声音来自我想要的地方。

  • pacmd set-card-profile 0 output:hdmi-stereo-extra1
  • pacmd set-card-profile 0 output:analog-stereo+input:analog-stereo
  • 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!

有没有办法检测HDMI是否插入,或者至少是否发生了变化?谢谢!

Linux Mint 18.2 Xfce x64, Asus P756U

Linux Mint 18.2 Xfce x64,华硕 P756U

回答by George Vasiliou

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

我使用两种不同的方法来确定是否插入了 HDMI:

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

a) 使用 xrandr
一个简单的 xrandr 会将您的 hdmi 显示器报告为已连接要在脚本中使用它,您可以执行以下操作:

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

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

以上将返回已连接的 hdmi 端口(即 HDMI-1),如果未连接 HDMI,则不返回任何内容。

You can then use something like

然后你可以使用类似的东西

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

zbecomes trueif $hdmi_activeis not set . ! zreverts this behavior and returns trueif hdmi_active has a value = hdmi is connected

z变为trueif$hdmi_active未设置。如果 hdmi_active 具有值 = hdmi 已连接,则! z恢复此行为并返回true

b) Using the HDMI status file:

b) 使用 HDMI 状态文件:

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

This returns connected / disconnected for your hdmi ports:

这将为您的 hdmi 端口返回连接/断开连接:

$ 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