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: command not found
If I try to run the function with bash without sudo (bash -c ‘my_func’), it works.
Any idea?
Starting from the answer of bmargulies, I wrote a function to cover this issue, which basically realizes his idea.
Example of usage:
running the following snippet
Will output
If you need to use this in a shell calling a function which is defined in your bashrc, as asked with a similar question on serverfault by another user, then you have to put the previous exesudo function on the same bashrc file as well, like the following:
Then you have to logout and login again or use
Finally you can use exesudo as follow: