I tried exporting the function and then executing it with bash, but that doesn\'t work:
$ export -f my_func
$ sudo bash -c \'my_func\'
bash: my_func: comma
An alternative to calling your function with sudo is to just move the "sudo " calls inside your function. For example, I was wanting to set up a shortcut function in OS X for forwarding localhost to a particular port.
function portforward() {
echo "y" | sudo ipfw flush;
sudo ipfw add 100 fwd 127.0.0.1,$1 tcp from any to any 80 in;
echo "Forwarding localhost to port $1!";
}
The function hits sudo and asks for my password. (Then pipes "y" to a prompt for ipfw, not related to this question). After that, sudo is cached so the rest of the function executes without the need to enter a password.
Essentially, this just runs like:
portforward 8000
Password:
Forwarding localhost to port 8000!
And fills my need because I only need to enter the password once and it's taken care of. Although it's a little ugly if you fail to enter the password the first time. Extra points for detecting whether the first sudo succeeded and exiting the function if not.