Is there a way to do this without installing extra packages?
2 Answers
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"

- 107,489
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

- 5,312
bash -c "rfkill list bluetooth|grep -q 'yes$' && rfkill unblock bluetooth || rfkill block bluetooth"
, which uses the status of the grep to either unblock or block bluetooth. This is in general a nice shorthand for if-statements in bash or shell scripts. – Joeytje50 Oct 01 '19 at 13:58