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

Disclaimer:


The Sample Scripts provided below are adapted from third-party Open-Source sites.

Check Bluetooth status

To check if Bluetooth is turned on/off on the device, use the script below.

If Output = 1, Bluetooth is ON

If Output =0, Bluetooth is OFF

Turn Bluetooth ON

To turn on Bluetooth, use the script below.

Instead of the single line killall, you can also use launchctl to restart the daemon.

Turn Bluetooth OFF

To turn off Bluetooth, use the script below.

Instead of the single line killall, you can also use launchctl to restart the daemon.

A detailed look at the process involved in changing the Bluetooth settings to on/off:

  • Edit Bluetooth daemon settings
  • 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

  • Restart the daemon
  • 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.

Notes:

  • Delay of few minutes can be expected while executing the script to turn Bluetooth on/off since it involves restarting the Bluetooth daemon.
  • It is recommended to manually validate the script execution on a system before executing the action in bulk.
  • Hexnode will not be responsible for any damage/loss to the system on the behavior of the script.