A tiny Swift program to run a command whenever the screen locks or unlocks
(I use it for locking other local machines' screens when locking the primary, and remounting network shares when waking from sleep)
# run-on-macos-screen-events <command-to-run-on-unlock> [command-args]
run-on-macos-screen-events ./examples/mount-network-shares.sh
# add to launchctl (start on login)
serviceman add --user \
--path "$PATH" \
./run-on-macos-screen-events ./examples/mount-network-shares.sh
Forked from coolaj86/run-on-macos-screen-unlock.
- Download
curl --fail-with-body -L -O https://github.com/smartwatermelon/run-on-macos-screen-events/releases/download/v1.1.0/run-on-macos-screen-events-v1.1.0.tar.gz
- Extract
tar xvf ./run-on-macos-screen-events-v1.1.0.tar.gz
- Allow running even though it's unsigned
xattr -r -d com.apple.quarantine ./run-on-macos-screen-events
- Move into your
PATH
mv ./run-on-macos-screen-events ~/bin/
You'll see notifications similar to these when adding launchctl services yourself:
-
Install
serviceman
curl --fail-with-body -sS https://webi.sh/serviceman | sh source ~/.config/envman/PATH.env
-
Register with Launchd
(changeCOMMAND_GOES_HERE
to your command)serviceman add --user \ --path "$PATH" \ ~/bin/run-on-macos-screen-events COMMAND_GOES_HERE
-
Download the template plist file
curl --fail-with-body -L -O https://raw.githubusercontent.com/smartwatermelon/run-on-macos-screen-events/main/examples/run-on-macos-screen-events.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 ./run-on-macos-screen-events.COMMAND_LABEL_GOES_HERE.plist ./run-on-macos-screen-events.example-label.plist mv ./run-on-macos-screen-events.*.plist ~/Library/LaunchDaemons/
-
Register using
launchctl
launchctl load -w ~/Library/LaunchAgents/run-on-macos-screen-events.*.plist
tail -f ~/.local/share/run-on-macos-screen-events.*/var/log/run-on-macos-screen-events.*.log
- Install XCode Tools
(includinggit
andswift
)xcode-select --install
- Clone and enter the repo
git clone https://github.com/smartwatermelon/run-on-macos-screen-events.git pushd ./run-on-macos-screen-events/
- Build with
swiftc
swiftc ./run-on-macos-screen-events.swift
- Git tag and push
git tag v1.1.x git push --tags
- Create a release
https://github.com/smartwatermelon/run-on-macos-screen-events/releases/new - Tar and upload
tar cvf ./run-on-macos-screen-events-v1.1.x.tar ./run-on-macos-screen-events gzip ./run-on-macos-screen-events-v1.1.x.tar open .
- How to run a command on lock/unlock (the snippets from which this repo grew)
- EventScripts
- HammarSpoon: caffeinate.watcher