Bash-连接USB设备时如何运行代码 [英] Bash - How to run code whenever USB device is connected
问题描述
我正在编写一个bash脚本,以自动检测USB键盘何时插入笔记本电脑(运行Ubuntu 14),因此可以自动更改键盘布局.
I am writing a bash script to automatically detect when my USB keyboard is plugged into my laptop (running Ubuntu 14), so I can change the keyboard layout automatically.
到目前为止,这是我的代码(我是从Stack Overflow的另一篇文章中获得的,所以我不确定100%如何工作)
Here is my code so far (I got it from another post on Stack Overflow so I'm not 100% sure how it works)
#!/bin/bash
setxkbmap es
for dev in /sys/bus/usb/devices/ *-*:*
do
if [ -f $dev/bInterfaceClass ]
then
if [[ "$(cat $dev/bInterfaceClass)" == "03" && "$(cat $dev/bInterfaceProtocol)" == "01" ]]
then
setxkbmap gb
fi
fi
done
到目前为止,我已经可以在启动时运行它了……但是我希望它每次连接或断开USB设备时都可以运行.
I have got this to run on startup so far... But I'd like it to run every time a USB device is connected or disconnected.
重要的是,我都必须在一个Bash脚本中运行它们,而不是在... udev/...或任何文件中以.rules文件的形式运行.但是,只有一个Python脚本也可以.
It is important that I have it all run in one Bash script and not as a .rules file in ...udev/... or anything. However, a single Python script will do just as well.
推荐答案
感谢 ralf htp 提出以下解决方案.它具有以下改进:
Thanks to ralf htp I was able to come up with the following solution. It has the following improvements:
- 它不依赖于特定的键盘,它将以相同的方式对待所有USB键盘.
- 如果用户手动切换到其他键盘布局(既不是默认键盘布局也不是USB键盘布局),它将不会自动将其切换回默认键盘布局或USB布局.
请随时通过 GitHub Gist
#!/bin/bash
kbd1=es #default keyboard layout
kbd2=gb #USB keyboard layout
flag=0
while true
do
layout="$(setxkbmap -query | grep -a layout | cut -c13-14)"
if [[ $layout == $kbd1 ]] || [[ $layout == $kbd2 ]]
then
for dev in /sys/bus/usb/devices*-*
do
if [ -f $dev/bInterfaceClass ]
then
if [[ "$(cat $dev/bInterfaceClass)" == "03" && "$(cat
$dev/bInterfaceProtocol)" == "01" ]]
then
if [[ "$flag" == "0" ]]
then
setxkbmap $kbd2
fi
flag=1
break
fi
if [[ "$flag" == "1" ]]
then
setxkbmap $kbd1
fi
flag=0
fi
done
fi
sleep 5s
done
这篇关于Bash-连接USB设备时如何运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!