A tiny Swift program to run a command whenever the screen locks or unlocks
(I use it for set my status offline or online at simple webpage)
# lock-observer [OPTIONS] <onlock_command> <onunlock_command>
lock-observer ./onlock ./onunlock# add to launchctl (start on login)
serviceman add --user \
--path "$PATH" \
./lock-observer ./examples/mount-network-shares.shForked from coolaj86/lock-observer. Another more professional fork smartwatermelon/run-on-macos-screen-events.
- Download
curl --fail-with-body -L -O https://github.com/coolaj86/lock-observer/releases/download/v1.0.0/lock-observer-v1.0.0.tar.gz
- Extract
tar xvf ./lock-observer-v1.0.0.tar.gz
- Allow running even though it's unsigned
xattr -r -d com.apple.quarantine ./lock-observer
- Move into your
PATHmv ./lock-observer ~/bin/
You'll see notifications similar to these when adding launchctl services yourself:
-
Install
servicemancurl --fail-with-body -sS https://webi.sh/serviceman | sh source ~/.config/envman/PATH.env
-
Register with Launchd
(changeCOMMAND_GOES_HEREto your command)serviceman add --user \ --path "$PATH" \ ~/bin/lock-observer COMMAND_GOES_HERE
-
Download the template plist file
curl --fail-with-body -L -O https://raw.githubusercontent.com/coolaj86/lock-observer/main/examples/lock-observer.COMMAND_LABEL_GOES_HERE.plist
-
Change the template variables to what you need:
USERNAME_GOES_HERE(the result of$(id -u -n)orecho $USER)COMMAND_LABEL_GOES_HERE(lowercase, dashes, no spaces)COMMAND_GOES_HERE(the example uses./examples/mount-network-shares.sh)
-
Rename and move the file to
~/Library/LaunchDaemons/mv ./lock-observer.COMMAND_LABEL_GOES_HERE.plist ./lock-observer.example-label.plist mv ./lock-observer.*.plist ~/Library/LaunchDaemons/
-
Register using
launchctllaunchctl load -w ~/Library/LaunchAgents/lock-observer.*.plist
tail -f ~/.local/share/lock-observer.*/var/log/lock-observer.*.log- Install XCode Tools
(includinggitandswift)xcode-select --install
- Clone and enter the repo
git clone https://github.com/coolaj86/lock-observer.git pushd ./lock-observer/ - Build with
swiftcswiftc ./lock-observer.swift
- Git tag and push
git tag v1.0.x git push --tags
- Create a release
https://github.com/coolaj86/lock-observer/releases/new - Tar and upload
tar cvf ./lock-observer-v1.0.x.tar ./lock-observer gzip ./lock-observer-v1.0.x.tar open .
- How to run a command on lock/unlock (the snippets from which this repo grew)
- EventScripts
- HammarSpoon: caffeinate.watcher