How to script bluetoothctl commands

I’m trying to script a series of commands with bluetoothctl, but it’s a bit tricky in some parts.

So what I have is a laptop with an additional bluetooth dongle since the builtin one isn’t working great, the builtin is the controller that’s always set as the default in bluetoothctl though.

What I want to do in a bash function/script:

  • bluetoothctl select (external dongle)
  • bluetoothctl scan on
  • (wait until a specific headset device is detected)
  • bluetoothctl pair (headset)
  • bluetoothctl connect (headset)
  • bluetoothctl trust (headset)

The main problem with the above is that the scan on command has no “until found” flag, I would like to scan until my headset is found. How would I solve that? I can’t grep the output because bluetoothctl doesn’t finish by itself, i.e. the scan command keeps running in the foreground.

Also the first command where I select the controller doesn’t seem to persist, if I run bluetoothctl select <dongle> and then bluetoothctl list, then the internal controller will still be shown as the default.