This is a small Objective-C program that will report the current sleeping/awake status of the attached displays. It makes use of the NSWorkspace ScreensDidSleep
and ScreensDidWake
Notifications, and uses a small LaunchAgent to subscribe to those events and keep the status current.
The program can be called on its own without arguments and will simply return a POSIX exit code of 0 (sleeping) or 1 (awake) to indicate the screen's status. So you can run something like:
if ! display-is-sleeping ; then echo "screen is awake!"; fi
or more concisely
display-is-sleeping || echo "screen is awake!"
Clone this repo (if you don't know how to do that, click the green Code button above, then Download ZIP). Once you have the bits on your disk, open a Terminal in the directory that contains the cloned files and run the command below:
./setup.sh --install
This will copy the binary to /usr/local/bin
(you can use a different directory if you like, by editing the setup script and changing the BINDIR
variable at the top). It also creates and starts up the LaunchAgent. From then on, you can use the display-is-sleeping
command in your scripts.
To Uninstall, simply re-run the script, passing --uninstall
:
./setup.sh --uninstall
This will unload and remove the LaunchAgent, stop any background processes and remove the command itself from wherever it was installed.
Example use in a script
if display-is-sleeping ; then
# ...put code here to run if the screen is dark
else
# ...code to run if the screen is awake
fi
Get current status as a string (prints true
or false
)
display-is-sleeping --status
Please report any bugs or issues you encounter. This idea was inspired by this AskDifferent post.