4

I wrote a small script to automate the connection of my bluetooth headphones to my linux machine.

#!/bin/bash

bluetoothctl
wait ${!}
connect XX:XX:XX:XX:XX:XX #headphone MAC address
wait ${!}
exit

The script opens bluetoothctl but doesn't run any of the following commands.

1
  • 2
    That's just not the way shell scripts work. Each command in a shell script is run by the shell. It does not somehow send that to sub-processes. In this case, bluetoothctl is run by the shell and then the shell will not execute the next line of the script until bluetoothctl exits. Need to use something like expect to "talk" to interactive programs.
    – kaylum
    Jan 25 '20 at 9:44
7

You can use bluetoothctl command in shell script as follow :

bluetoothctl -- command

or:

echo -e "command\n" | bluetoothctl

e,g:

bluetoothctl -- connect XX:XX:XX:XX:XX:XX
3
bluetoothctl -- pair XX:XX:XX:XX:XX:XX
sleep 10
bluetoothctl -- trust XX:XX:XX:XX:XX:XX
bluetoothctl -- connect XX:XX:XX:XX:XX:XX
sleep 5

works like a charm. Its especially useful when adding "sleep" delays between pair, trust and connect under bluetoothctl to give it time to discover and setup the BT devices.

Something like

bluetoothctl <<EOF
pair XX:XX:XX:XX:XX:XX
sleep 10
exit
EOF

would not work because sleep is not recognized as a command under bluetoothctl.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.