I have a Mac for work, and an external monitor. I like love the Night Shift option, but the setting won’t stay on after I unplug said external monitor. After trolling around a while on the internets, I found a couple scripts, but putting them in cron killed the preferences daemon and some other stuff, which would interrupt my Bluetooth headset and kill my vibe while listening to music. More importantly, it could have interrupted meetings, resulting in me nervously trying to figure out what past me did to put myself in such a situation.

Aaaanyway, I learned some (kind of) fun stuff about preference lists in Mac, how to print and set settings in them using PlistBuddy, and so on. Below is the script I came up with, maybe it will help someone else struggling with the same thing.

The below assumes you’ve added yourself or your group to sudoers with the NOPASSWD option set (scary, perhaps). Would be happy to receive input on how to do that part better… for now, I think an hour spent on this is long enough.

#!/bin/bash

function usage(){
	echo "Usage: $0 [enable|disable]"
	exit 1
}

if [[ $1 == "disable" ]]; then
	# Disable settings
	desiredAlgoOverride=3
	desiredEnabled=0
elif [[ $1 == "enable" ]]; then
	desiredAlgoOverride=4
	desiredEnabled=1
else
	usage
fi

plistLoc="/private/var/root/Library/Preferences/com.apple.CoreBrightness.plist"
currentUserUID="CBUser-$(dscl . -read /Users/$(whoami)/ GeneratedUID | cut -d' ' -f2)"

# Enable settings
actualAlgoOverride=$(sudo /usr/libexec/PlistBuddy -c "Print :$currentUserUID:CBBlueReductionStatus:BlueLightReductionAlgoOverride" $plistLoc)
actualEnabled=$(sudo /usr/libexec/PlistBuddy -c "Print :$currentUserUID:CBBlueReductionStatus:BlueReductionEnabled" $plistLoc)

if [ $desiredAlgoOverride -eq $actualAlgoOverride -a $desiredEnabled -eq $actualEnabled ]; then
	exit 0
fi

# Change the settings directly in the core brightness plist (defaults doesn't deal with nested data structures well)
sudo /usr/libexec/PlistBuddy -c "Set :$currentUserUID:CBBlueReductionStatus:BlueLightReductionAlgoOverride $desiredAlgoOverride" $plistLoc
sudo /usr/libexec/PlistBuddy -c "Set :$currentUserUID:CBBlueReductionStatus:BlueReductionEnabled $desiredEnabled" $plistLoc
sudo /usr/libexec/PlistBuddy -c "Set :$currentUserUID:CBBlueReductionStatus:BlueLightReductionAlgoOverrideTimestamp `date`" $plistLoc

sudo killall cfprefsd
sudo killall corebrightnessd