Skip to content

Instantly share code, notes, and snippets.

@brunerd
Created March 20, 2021 16:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunerd/5ba75737b2093e88eb30aa614584a21b to your computer and use it in GitHub Desktop.
Save brunerd/5ba75737b2093e88eb30aa614584a21b to your computer and use it in GitHub Desktop.
Detect the macOS CoreGraphics Screen Lock status of the console user via ioreg
#!/bin/sh
#Joel Bruner (https://github.com/brunerd)
function screenIsLocked { [ "$(/usr/libexec/PlistBuddy -c "print :IOConsoleUsers:0:CGSSessionScreenIsLocked" /dev/stdin 2>/dev/null <<< "$(ioreg -n Root -d1 -a)")" = "true" ] && return 0 || return 1; }
function screenIsUnlocked { [ "$(/usr/libexec/PlistBuddy -c "print :IOConsoleUsers:0:CGSSessionScreenIsLocked" /dev/stdin 2>/dev/null <<< "$(ioreg -n Root -d1 -a)")" != "true" ] && return 0 || return 1; }
if screenIsLocked; then
echo "Screen locked"
fi
if screenIsUnlocked; then
echo "Screen unlocked"
fi
if ! screenIsLocked; then
echo "Screen unlocked (inverse logic)"
fi
if ! screenIsUnlocked; then
echo "Screen locked (inverse logic)"
fi
@kargirwar
Copy link

Is this portable across MacOS versions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment