This scenario is for people who want to put their Macs to sleep after a certain activity that you know will take ‘x’ amount of time, like: watching a movie, downloading a file.
In other words: auto shutdown Mac after certain amount of time.
There’s quite a few apps that might do this for you, but I’m going to show you how to do it the geeky way using the Terminal 🙂
Let’s say you’re going to watch a 2h movie and you want your Mac to go to sleep right after it finishes. Open your Terminal and write:
sleep $[120*60]; osascript -e ‘tell application “System Events” to sleep’
The first part with ‘sleep’ calculates the number of seconds in 120 minutes using bash’s arithmetic expressions and passes it to the ‘sleep’ function. After ‘sleep’ wakes up, we run a simple script that puts your Mac to sleep. Of course you can put any amount of time you need (it’s usually better to put too much than too little 😉 )
If you plan on using this quite often, it’s best to write a short script:
#!/bin/bash
d=$1
while [ -z $d ]; do
read -p “Duration (minutes): ” d
done
sleep $[$d*60]
echo “. . . z z z Z Z Z”
osascript -e ‘tell application “System Events” to sleep’
Save it somewhere in your path, if you can (enabling and using “root” user in Mac OS X), remember to do a ‘chmod +x’ on the file and you’re ready to go.
If you don’t want to use “root”, put it somewhere in your user directory e.g. make a directory “scripts” in “Library” and put your script there.
Create a “.bash_login” script file that will append your private scripts directory to the current path:
#!/bin/bash
PATH=$PATH:/Users/mateusz/Library/scripts
If you’re ready, just pass the number of minutes as an argument (I called my script “sleepafter”):
bash-3.2$ sleepafter 120
The “while” loop in my script makes sure that “sleep” has a value to work with. This way you can easily run the script from Spotlight:
bash-3.2$ sleepafter
Duration (minutes): 60
If you are invoking a task that ends the application process after finishing, then simply add the “put to sleep” script at the end. E.g. when compiling something:
make; make install; sleepafter now
E.g. when using applications like ‘wget’ for downloading files:
Let me know, if you have any good ideas on modifying that script!
That is all 🙂