![如何将 dmesg 输出中的匹配词保存到列表中](https://linux22.com/image/1442263/%E5%A6%82%E4%BD%95%E5%B0%86%20dmesg%20%E8%BE%93%E5%87%BA%E4%B8%AD%E7%9A%84%E5%8C%B9%E9%85%8D%E8%AF%8D%E4%BF%9D%E5%AD%98%E5%88%B0%E5%88%97%E8%A1%A8%E4%B8%AD.png)
我使用不同的端口将 USB-串行设备连接到我的设备,串行 USB 设备有时显示为“ttyUSB0”,有时显示为“ttyUSB1”或“ttyUSB2”。
我如何编写脚本从该命令中提取所有 ttyUSB 名称:
deviceNodes = "$(sudo dmesg tail | egrep -i 'ttyUSB')"
echo "${deviceNodes}"
for i in "${deviceNodes[@]}"
do
udevadm info -a -n /dev/ttyUSB1 | grep '{serial}' | head -n1
done
并将其保存在变量中并循环列表中的项目?
以下是 dmesg 命令的输出:
[37606.832517] usb 2-1.1: FTDI USB Serial Device converter now attached to ttyUSB0
[37664.565271] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[37695.844687] usb 2-1.1: FTDI USB Serial Device converter now attached to ttyUSB0
[38017.111961] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[38490.802048] usb 2-1.1: FTDI USB Serial Device converter now attached to ttyUSB0
[38776.225985] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[38778.317840] usb 2-1.1: FTDI USB Serial Device converter now attached to ttyUSB0
[38874.027395] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[38876.631579] usb 2-1.1: FTDI USB Serial Device converter now attached to ttyUSB0
[39040.443963] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[39796.942837] usb 2-1.2: FTDI USB Serial Device converter now attached to ttyUSB0
[39802.674018] usb 2-1.1: FTDI USB Serial Device converter now attached to ttyUSB1
[40372.029798] ftdi_sio ttyUSB1: FTDI USB Serial Device converter now disconnected from ttyUSB1
[40372.156024] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[41642.886671] usb 2-1.1: FTDI USB Serial Device converter now attached to ttyUSB0
答案1
> deviceNodes = "$(sudo dmesg tail | egrep -i 'ttyUSB')"
这是语法错误。变量赋值时等号两边不能有空格。另请参阅http://mywiki.wooledge.org/BashPitfalls#foo_.3D_bar
此外,如果您只想迭代实际匹配项,则需要更改表达式以仅提取那些匹配项。 试试这个。
dmesg | grep -Eo 'ttyUSB[0-9]+' | sort -u |
while read devnode; do
udevadm info -a -n /dev/"$devnode" | grep '{serial}' | head -n1
done
(在我的系统上,无需任何参数即可正常dmesg
运行。)sudo
tail
答案2
这难道不是简单地改变以下内容吗?
deviceNodes = "$(sudo dmesg tail | egrep -i 'ttyUSB')"
对此?
deviceNodes="$(cat temp | egrep -i 'ttyUSB' | sed 's/^.*tty/tty/' )"
‘i’ 显然是您需要迭代的变量。
测试如下。
echo "[37664.565271] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0" | sed 's/^.*tty/tty/'
ttyUSB0