Category filter
Script for Bluetooth Control in macOS devices
Changing the devices’ Bluetooth Settings requires the user to modify the Bluetooth settings from the System Preferences. As an administrator, if you want to check and modify the Bluetooth power state of the device without involving direct user interaction, the Execute Custom Script is here to help you.
You can use the below shell script to check the Bluetooth state and turn it on/off with a single line command.
Scripting Language – Bash
File extension – .sh
Check Bluetooth status
To check if Bluetooth is turned on/off on the device, use the script below.
1 2 |
#!/bin/sh $ defaults read /Library/Preferences/com.apple.Bluetooth ControllerPowerState |
If Output = 1, Bluetooth is ON
If Output =0, Bluetooth is OFF
Turn Bluetooth ON
To turn on Bluetooth, use the script below.
1 2 3 |
#!/bin/sh $ sudo defaults write
/Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 1
$ sudo killall -HUP bluetoothd #or blued based on macOS version |
Instead of the single line killall
, you can also use launchctl
to restart the daemon.
1 2 3 4 |
#!/bin/sh $ sudo defaults write
/Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 1
$ sudo launchctl stop com.apple.bluetoothd #or blued based on macOS version $ sudo launchctl start com.apple.bluetoothd |
Turn Bluetooth OFF
To turn off Bluetooth, use the script below.
1 2 3 |
#!/bin/sh $ sudo defaults write
/Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 0
$ sudo killall -HUP bluetoothd #or blued based on macOS version
|
Instead of the single line killall
, you can also use launchctl
to restart the daemon.
1 2 3 4 |
#!/bin/sh $ sudo defaults write
/Library/Preferences/com.apple.Bluetooth ControllerPowerState -int 0 $ sudo launchctl stop com.apple.bluetoothd #or blued based on macOS version $ sudo launchctl start com.apple.bluetoothd |
A detailed look at the process involved in changing the Bluetooth settings to on/off:
- Edit Bluetooth daemon settings
- Restart the daemon
sudo
– enables users to run programs with elevated security privileges.
defaults
– defaults tool works directly with the macOS preferences subsystem and is used to manage preferences and other settings.
/Library/Preferences/com.apple.Bluetooth
– Location of Bluetooth daemon
ControllerPowerState
– Set value to 1 for ON and 0 for OFF
killall
– kill processes by name sending a signal to all processes running any of the specified commands. On a macOS system which has proctools installed, you can replace killall
to pkill
.
HUP
– “hangup signal” is usually sent to a program to request that it restarts and re-reads all its configuration in the process.
bluetoothd
– macOS Bluetooth daemon.
launchctl
– Interfaces with launchd to load, unload daemons/agents and control launchd.