Turn Bluetooth On and Off from Command Line on macOS

Sometimes I take my laptop away from my desk, but the connection to my bluetooth mouse is still strong enough to stay connected. It will be just strong enough to prevent the trackpad from enabling, so I can't mouse up to the menu to turn off Bluetooth.

Same problem in reverse when I get back to the desk and dock; the mouse won't connect because I disabled Bluetooth.

Goal: a command-line way to enable or disable bluetooth.

I found blueutil, here is how to use it.

Installation

brew install blueutil

Use

There is a command line flag -p for turning Bluetooth on/off with a 1 || 0.

# Turn bluetooth off by passing a 0
blueutil -p 0

# Turn bluetooth on by passing a 1
blueutil -p 1