Quick Tip: caffeinate your Terminal
Quick tips are random posts regarding something I discovered on my way to something bigger. They usually get longer than “quick” would imply, for which I refuse to apologize.
Another random OS X command line exposé…
There’s a command called
caffeinate that does exactly what the app Caffeine does — keep your computer from sleeping — but it lets you do it from scripts and the command line.
This command can be run in a couple of ways. First, you can add a timer and tell it to prevent sleep for a certain duration. Alternatively, you can attach it to another command to keep the computer awake as long as that process is running, allowing the system to sleep after the command finishes.
It handles different aspects of system sleep: display sleep, idle sleep, disk sleep and “system sleep.” It’s also handy to know that it can wake up your display through a script or SSH session.
You can see the man page for a full list of options, but here are a couple of examples:
Keep your computer awake for 1 hour:
caffeinate -t 3600 &
-t argument is based on seconds, so an hour is 60 * 60 (3600). Note that you can still sleep your computer manually when caffeinate is running.
In case you’re unfamiliar, the ampersand at the end causes the command to run in the background, freeing up your command line. If you’re running it from something like an AppleScript or Automator, this won’t help. Your script or workflow will keep running until the timer ends. Depending on how you trigger it, that might not be a big deal. In LaunchBar you, you can activate it with Option-Return instead of just Return and it will run the whole script in the background. I’m not sure how Alfred or others handle this.
Keep your computer from idling until a Terminal command finishes
caffeinate -i long_running_script.sh
-i prevents “idle sleeping.” Other options include:
-djust prevents the display from sleeping
-mjust prevents disks from sleeping when idle
-skeeps the whole system awake
Wake up your computer
caffeinate -u -t 1
-u replicates user activity. It causes the same reaction as moving a mouse or hitting a key after your Mac sleeps. Without a
-t argument to set a timeout, it’s supposed to default to 5 seconds, but it seems to hang around a lot longer than that on my system. A single second of user activity is all it takes to wake a machine.
If you need to wake up a monitor from another machine and have a keyless login set up, you can run
ssh mymac.local 'caffeinate -u -t 1' from a script or the command line to give it a wakeup call. Or keep it awake for a period of time with
ssh mymac.local 'caffeinate -u -t 14400' &
That’s really all there is to it. Just another semi-hidden OS X-only command that you might have missed.