Stop a Mac from sleeping while a bash script is running, then allow it to sleep as normal once complete

I've got my Mac to wake up during the night and run an rsync to back it up. This is configured through Energy Saver > Schedule.

However it seems that it's going back to sleep before it can get anything done, so I need to stop it sleeping during the execution of the bash script that rsync runs from.

I figured the best way (if it's possible) is to issue a command to set the sleep timeout to "Never" or a very long timeout before it rsyncs and then back to normal once it's complete. Is there a better solution for doing this?


Caffeinate

For example:

caffeinate -i rsync -avz someuser@somehost:somefolder /some/local/folder

From the man page:

EXAMPLE
     caffeinate -i make
        caffeinate forks a process, execs "make" in it, and holds an
        assertion that prevents idle sleep as long as that process
        is running.

See man caffeinate for details.


Mac OS X 10.8 (Mountain Lion) and later

Use the caffeinate command. See Nathan Long's answer or man caffeinate for details.

Mac OS X 10.7 (Lion) and earlier

It's buried in the manual page, but pmset has a very simple mode for preventing sleep. If you execute the command pmset noidle your Mac will be kept awake until that process is killed. Here is how to use it in a script:

# launch process to prevent sleep and move it to the background
pmset noidle &
# save the process ID
PMSETPID=$!

... do stuff here ...
... don't fall asleep ...
... watch out for that tree!
... ok we're free and clear now ...

# kill pmset so the computer can sleep if it wants to
kill $PMSETPID

This is better than using pmset to change your sleep settings, which requires root access and (assuming you want to be a good citizen) some way of detecting the current settings and changing them back when you're done.


Try

man pmset

:-)