Skip to content

Instantly share code, notes, and snippets.

@cdzombak
Last active January 20, 2023 14:31
Show Gist options
  • Save cdzombak/efb3ae821952b2b5faed496bd7a3c9c8 to your computer and use it in GitHub Desktop.
Save cdzombak/efb3ae821952b2b5faed496bd7a3c9c8 to your computer and use it in GitHub Desktop.
telling if macOS screen is locked from bash script
#!/usr/bin/env bash
set -euo pipefail
# from https://stackoverflow.com/a/66723000
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment