4

Is there a way to do this without installing extra packages?

giorgi nguyen
  • 143
  • 1
  • 6

2 Answers2

10

You can control whether your bluetooth signal is enabled with rfkill. Wrapping this in a little Bash conditional allows you to toggle the state easily:

#!/bin/bash
if rfkill list bluetooth | grep -q 'yes$' ; then 
    rfkill unblock bluetooth
else
    rfkill block bluetooth
fi

You could save the above in a script file anywhere (e.g. ~/bin/toggle-bluetooth) and make it executable (chmod +x FILENAME) to be able to bind that command to a keyboard shortcut in the system settings.

Alternatively, you can put it in a single line bash command and directly paste that into the shortcut:

bash -c "if rfkill list bluetooth|grep -q 'yes$';then rfkill unblock bluetooth;else rfkill block bluetooth;fi"
Byte Commander
  • 110,243
0

If you want to not only toggle bluetooth itself, but also the connection to a specific device, you could use the script below. I use it in Ubuntu 20.04 to toggle my bluetooth connection to my speakers. It checks if the connection is already established or not and toggles it accordingly.

Note that it has the MAC address of my speakers hardcoded.

!/bin/bash

Toggle connection to bluetooth device

mac="90:03:B7:17:00:08" # DEH-4400BT

if bluetoothctl info "$mac" | grep -q 'Connected: yes'; then echo "Turning off $mac" bluetoothctl disconnect || echo "Error $?" else echo "Turning on $mac" # turn on bluetooth in case it's off rfkill unblock bluetooth

bluetoothctl power on
bluetoothctl connect "$mac"
sink=$(pactl list short sinks | grep bluez | awk '{print $2}')

if [ -n "$sink" ]; then
    pacmd set-default-sink "$sink" && echo "OK default sink : $sink"
else
    echo could not find bluetooth sink
    exit 1
fi

fi

mivk
  • 5,811