How to make a Mac sleep via SSH
So now that I knew how to wake my MacBook remotely, I needed a way to make it go to sleep when I’m done using it. Doing a little bit of Googling and playing, I’ve come up with the following shell script, which I’ve called ‘gotosleep’:
#!/bin/bash
echo Going to sleep in 30 seconds...
sleep 30
osascript -e 'tell application "System Events" to sleep'
However, if I issue the command, and then logout while it is waiting on the sleep command, the osascript command won’t execute. Thus, I need to run my script like this:
nohup ~/gotosleep &
nohup instructs OS X to continue running the command even if my terminal session ends. To make things easier, I aliased the above in my bash_profile. Thanks to a suggestion, I also added the output redirect to /dev/null to prevent files from being created every time I call my alias:
alias gotosleep=’nohup ~/gotosleep > /dev/null &’
So I can just type ‘gotosleep’ in any directory, logout, and know the MacBook will go to sleep 30 seconds later.
Edit 6/16/08: cowsandmilk has pointed out a good tip—I’ve modified the alias above to reflect it. Thanks!