Last active
March 26, 2023 13:22
-
-
Save Axlfc/368d8494385568f084041f56a2b2b6ae to your computer and use it in GitHub Desktop.
Bluetooth bash function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Description: Control Bluetooth via console commands using only one function. | |
# Argument 1: 'on'; 'off'; 'show'; 'connect'; 'disconnect'; 'scan'; 'pair' | |
# Argument 2 (connect, disconnect, pair): A Bluetooth device name | |
bluetooth() { | |
if [ "$1" = "on" ]; then | |
sudo rfkill unblock bluetooth | |
echo "Bluetooth Enabled" | |
elif [ "$1" = "off" ]; then | |
sudo rfkill block bluetooth | |
echo "Bluetooth Disabled" | |
elif [ "$1" = "show" ]; then | |
echo "Bluetooth Devices:" | |
bluetoothctl devices | |
elif [ "$1" = "connect" ]; then | |
if rfkill list bluetooth | grep -q "Soft blocked: yes"; then | |
sudo rfkill unblock bluetooth | |
sleep 1 | |
echo "Bluetooth Enabled" | |
fi | |
device_name="$2" | |
device_mac="$(bluetoothctl devices | grep -i "$2" | cut -d " " -f2)" | |
if [ -z "${device_mac}" ]; then | |
echo "Device not found: ${device_name}" | |
return 1 | |
fi | |
bluetoothctl connect "${device_mac}" &>/dev/null | |
echo "${device_name} (${device_mac}) Connected" | |
elif [ "$1" = "disconnect" ]; then | |
device_name="$2" | |
device_mac="$(bluetoothctl devices | grep -i "$2" | cut -d " " -f2)" | |
if [ -z "${device_mac}" ]; then | |
echo "Device not found: ${device_name}" | |
return 1 | |
fi | |
bluetoothctl disconnect "${device_mac}" &>/dev/null | |
echo "${device_name} (${device_mac}) Disconnected" | |
elif [ "$1" = "scan" ]; then | |
bluetoothctl scan on | |
elif [ "$1" = "pair" ]; then | |
device_name="$2" | |
device_mac="$(bluetoothctl devices | grep -i "$2" | cut -d " " -f2)" | |
if [ -z "$device_mac" ]; then | |
echo "Device not found: ${device_name}" | |
return 1 | |
fi | |
echo "Pairing with ${device_name} (${device_mac})..." | |
bluetoothctl pair "${device_mac}" &>/dev/null | |
else | |
if rfkill list bluetooth | grep -q "Soft blocked: yes"; then | |
sudo rfkill unblock bluetooth | |
echo "Bluetooth Enabled" | |
else | |
sudo rfkill block bluetooth | |
echo "Bluetooth Disabled" | |
fi | |
fi | |
} | |
# Description: Toggle connect/disconnect with Echo Dot-1V5 | |
echodot() { | |
if rfkill list bluetooth | grep -q "yes"; then | |
sudo rfkill unblock bluetooth | |
sleep 2 | |
echo "Bluetooth Enabled" | |
fi | |
device_mac="$(bluetoothctl devices | grep -i "Echo Dot-1V5" | cut -d " " -f2)" | |
if bluetoothctl info "${device_mac}" | grep -q "Connected: yes"; then | |
bluetooth disconnect "Echo Dot-1V5" | |
else | |
bluetooth connect "Echo Dot-1V5" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment