Mac's caffeinate tool accepts the name of a utility: caffeinate sleep 1, for instance. Is there any way for it to accept a function as well? For example:

function mysleep {
  sleep 2

caffeinate mysleep    # mysleep: No such file or directory

caffeinate launches executables. However, shell functions exist only within the shell. Shell functions are not executables.

Workaround: call bash directly

This works best for one-liners and simple commands.

caffeinate bash -c 'sleep 2'

Multi-liners work too:

caffeinate bash <<EOF
  sleep 2
  echo "done :D"

Workaround: call a script instead of a function

Instead of doing your work inside a function, split it out into a separate script:

caffeinate mysleep.sh
# mysleep.sh
sleep 2

Per the man page:

caffeinate -- prevent the system from sleeping on behalf of a utility

A function is not a utility as a utility will have a process ID (pid) associated with it. When you specify a utility, caffeinate forks a process and holds an assertion that prevents sleep until that process is complete.


caffeinate requires that there be an object to run, a function does not fill this requirement.

Change your function into a shell script and it will work fine. So for your example:

sleep 2

saved into a file called mysleep and then caffeinate mysleep will work fine (so long as the file mysleep is in your system PATH.).


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .