如何将 dmesg 输出中的匹配词保存到列表中

如何将 dmesg 输出中的匹配词保存到列表中

我使用不同的端口将 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运行。)sudotail

答案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

相关内容