Initially some time in 2020 I was looking for a way to trigger some custom actions when I put my Macbook Pro to sleep. I found someone asked this same question in 2011 on Apple Stake Exchange
The best answer, which was the newest when I came across the article was this.
Sleepwatcher
Was interested in that question previously but didn’t find any step by step guide on how to achieve it. Solution is based on open-source tool called sleepwatcher and apple launchd Was inspired by this article
- Install sleepwatcher:
brew install sleepwatcher
- First create:
~/.wakeup
and~/.sleep
scripts and put some shell logic in them. - Add necessary permissions:
chmod 700 ~/.sleep && chmod 700 ~/.wakeup
- Test it locally:
/usr/local/sbin/sleepwatcher --verbose --sleep ~/.sleep
- go to sleep with running terminal
- If it works then load the process as launchd agent for all users:
Library/LaunchAgents
- Add symlink for the sleepwatcher launchd task (replacing
{version}
with the version you have installed):sudo ln -sfv /usr/local/Cellar/sleepwatcher/{version}/de.bernhard-baehr.sleepwatcher-20compatibility.plist /Library/LaunchAgents/
- Load launchd task:
sudo launchctl load /Library/LaunchAgents/de.bernhard-baehr.sleepwatcher-20compatibility.plist
Thanks for the write up Dzmitry Hubin!