bt.sh
#!/bin/bash
echo -e 'scan onn'
sleep 2
echo -e 'devicesn'
echo -e 'quitn'
如果我将上述文件通过管道传输到蓝牙ctl,它会按预期工作。
# ./bt.sh | bluetoothctl
但是我如何作为内联脚本做到这一点,我已经尝试了以下内容,但它不起作用,并且蓝牙 ctl 似乎没有注册命令:
echo -e 'scan on' | bluetoothctl && sleep 2 && echo -e 'devicesn' | bluetoothctl && echo -e 'quitn' | bluetoothctl;
使用命令列表:
{ printf 'scan onnn'
sleep 2
printf 'devicesnn'
printf 'quitnn'
} | bluetoothctl
这是一个完整的示例,说明如何与蓝牙 ctl 交互并获取其输出。命名管道用于馈送蓝牙ctl。您可以修改函数bleutoothctl_writer以从文件中读取命令
#!/bin/bash
pipe=/tmp/btctlpipe
output_file=/tmp/btctl_output
if [[ ! -p $pipe ]]; then
mkfifo $pipe
fi
trap terminate INT
function terminate()
{
killall bluetoothctl &>/dev/null
rm -f $pipe
}
function bleutoothctl_reader()
{
{
while true
do
if read line <$pipe; then
if [[ "$line" == 'exit' ]]; then
break
fi
echo $line
fi
done
} | bluetoothctl > "$output_file"
}
function bleutoothctl_writer()
{
cmd=$1
printf "$cmdnn" > $pipe
}
bleutoothctl_reader &
sleep 1
bleutoothctl_writer "scan on"
sleep 15
bleutoothctl_writer "scan off"
sleep 1
bleutoothctl_writer "devices"
sleep 1
bleutoothctl_writer "exit"
device_list=$(cat $output_file | grep -e '^Device.*' | sed 's/Device //g')
echo "$device_list"
terminate