In a previous article, I showed how to use Wake-on-LAN to remotely wake a sleeping Mac. I often log on to my home Mac remotely using SSH via my Solaris home server, waking it in the process. With the default settings, the machine will go back to sleep after a few minutes of inactivity.

I recently changed my system defaults to never make the machine sleep, however, because OS X’s sleep functionality will cause the system to sleep even when active Unix jobs are running, like long compiles. That is because the OS has no way of distinguishing between live applications and background daemons. There does not seem to be a command-line utility allowing the user to put the machine to sleep, however, so I quickly wrote one, using Apple Q&A 1134 as a starting point.

You can download the command and source code (including a Panther binary) here: macsleep-1.0.tar.gz (Tiger and Intel users, see below for 1.1)

Restrictions: this command will only work if the user ID it is being executed from matches the user ID of the currently logged on user (not a problem for me because I have auto-logon enabled).

Update (2003-12-06):

Mike Harris reports another similar utility already exists, SleepNow.

Update (2005-11-30):

Kalvis Jansons suggests using AppleScript and the System Events application introduced in 10.3 to achieve the same results, using the following shell script:

#!/bin/bash
osascript << EOT
tell application "System Events"
     sleep
end
EOT

Update (2006-04-02):

I have rebuilt the program for Tiger in both Intel and PowerPC flavors, as well as a universal binary. The new version is macsleep-1.1.tar.gz. The source code itself is unchanged.