MacOS – Run a program/script when the screen is locked or unlocked

applescriptauthenticationmacos

Is there a way to run a specified script or program when the screen is locked or unlocked? Ideally a bash function or an AppleScript.

Is there an event that I could subscribe to that would allow me to do that? Or an existing app that supports this?

Best Answer

After some searching, I found SleepWatcher, a free tool that allows to run a script when the screen goes to sleep or wakes up.

After installing it, you can link a shell script that is run on one of the available events (which include dim screen, wake up screen, computer sleep, wake up computer and some more). From the shell script, I can run a command, or call an AppleScript that I want to run on these events.

Since my screen goes to sleep when I lock my computer, this is exactly what I was looking for.

You can see it in action here: https://github.com/nwinkler/sleepwatcher-lync-status