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!

Notes

  1. free-bets reblogged this from caseyliss
  2. cowsandmilk reblogged this from caseyliss and added:
    awesome tip, but one thing to add. nohup creates nohup.out files wherever you are, so if you don’t want to spew these in...
  3. macz reblogged this from soupsoup
  4. vland reblogged this from marco
  5. soupsoup reblogged this from jstn and added:
    i’m bookmarking this for when i get my new battery. i’m trying to be a more responsible mac book owner this time around!
  6. jstn reblogged this from marco and added:
    I’ve always wondered about this!
  7. tyzm reblogged this from vmconverter
  8. vmconverter reblogged this from marco
  9. marco reblogged this from caseyliss and added:
    Mac for less than...he’s already teaching us new things. With wake-on-LAN
  10. caseyliss posted this