Expect脚本中bluetoothctl write命令添加引号报错求助
解决Expect脚本中bluetoothctl write命令双引号传递问题
在你的Expect脚本中,直接写入双引号会被脚本当作字符串边界解析,导致语法错误。要把双引号正确传递给bluetoothctl执行,需要用Expect的字符串转义规则处理,或者使用大括号语法原样发送内容。
修正后的脚本
#!/usr/bin/expect -f set prompt "#" set address 34:85:18:6a:52:52 set write_data "0xa5 0x00 0x00 0x08 0x00 0x53 0x6f 0x0e 0x00 0x03 0x10 0x01 0x02 0x12 0x01 0x0a 0xff 0x01 0x20 0x9a" spawn bluetoothctl expect -re $prompt send "connect $address\r" expect "Connection successful" sleep 2 send "list-attributes\r" sleep 2 send "menu gatt\r" sleep 2 send "select-attribute /org/bluez/hci0/dev_34_85_18_6A_52_52/service002e/char002f\r" sleep 2 send "list-attributes\r" sleep 2 # 方式1:用反斜杠转义双引号,确保双引号被发送给bluetoothctl send "write \"$write_data\"\r" # 方式2:用大括号包裹命令,括号内内容原样发送,无需转义 # send {write "0xa5 0x00 0x00 0x08 0x00 0x53 0x6f 0x0e 0x00 0x03 0x10 0x01 0x02 0x12 0x01 0x0a 0xff 0x01 0x20 0x9a"\r} send "quit\r" expect eof
关键说明
- 当用双引号包裹send的内容时,内部的双引号必须用
\"转义,否则Expect会误判字符串结束位置,引发语法错误。 - 使用大括号
{}包裹整个命令是更省心的方式:大括号内的所有字符都会被原样发送,不需要转义任何符号,适合内容复杂的命令场景。 - 将写入数据单独存为变量
write_data,可以让脚本更易维护,修改数据时无需改动命令发送逻辑。
内容的提问来源于stack exchange,提问作者iUncleMike
相关产品推荐
相关产品推荐

