How to caffeinate a function on CLI? 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 &lt;&lt;EOF
  sleep 2
  echo "done :D"
EOF


You can use functions:

caffeinate bash &lt;&lt;EOF
  function mysleep {
    sleep 2
  }
  mysleep
EOF


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




#!/bin/bash
# mysleep.sh
sleep 2