macOS: use caffeinate to keep your computer on

What your coffee looks like before you get it.

If you’re starting a long job on your Apple Macintosh Computer and wandering off for a coffee, the machine may go to sleep before it finishes due to inactivity. To prevent that from happening, also give your computer a boost with the caffeinate command, a macOS built-in since 2012 (OS X Mountain Lion).

Basic usage

Pass your command to caffeinate as arguments:

$ caffeinate ./migrate.sh

In this wrapper form, caffeinate will run your command and keep the machine awake for as long as it runs, then let sleep resume as soon as it finishes.

Bare usage

For the quickest of caffeine fixes, you can run caffeinate on its own. It will hold the machine awake until you interrupt it with Ctrl-C:

$ caffeinate

...

^C

This is the form I have normally run when I have the realization but want to rush off to make my cuppa tea.

Caffeinate a job that’s already running

To skip the quick fix and allow your computer to rest after an already-running job finishes, use the -w option to caffeinate until a waited-for process ID (PID) exits:

$ caffeinate -w <PID>

Find the PID however you like, such as with Activity Monitor or pgrep. My favourite is to temporarily pause and resume the target process, which I do in Zsh with Ctrl-Z and then %1:

$ ./migrate.sh
...

^Z
[1]  + 90498 suspended  ./migrate.sh

$ %1
[1]  + 90498 continued  ./migrate.sh

The number 90498 is the PID, which you can then caffeinate in a second terminal tab:

$ caffeinate -w 90498

Keep the display on too

By default, caffeinate prevents idle sleep, which is the system nodding off after a period of no input. This is its default-on -i option.

The -d option prevents display sleep, which is the display dimming and turning off after a period of no input. Doing so is handy when you want to occasionally glance at the progress of your long-running job.

To use -d, combine it with -i to re-select the idle sleep prevention:

$ caffeinate -id ./migrate.sh

Things caffeinate won’t do

Fin

My rule: no caffeine without theanine. Get yourself some nice green tea,

—Adam


Read my book Boost Your Git DX to Git better.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: