How to enable `sudo` with custom functions

aliasfunctionsudo

Recently I learned you can enable sudo for custom aliases as follows:

alias sudo='sudo ' # note: the space is required!

The reason this works is the following:

If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion.

My question is: is there any way to enable sudo with custom functions too?

Best Answer

In the general case what you're trying to do doesn't really work.

With aliases, there is pretty much just a string rewrite before the line is passed for execution.

So, for example, if you have

alias sudo='sudo '
alias foo='bar baz'

then when you enter sudo foo the command line is rewritten to sudo bar baz and that is then what is run. This is simple command line rewriting.

Now functions are harder. They're not simple rewrites, but a complete evaluation; they can set variables, change directories, open files... pretty much do anything the shell can do. And, importantly, they're run in the context of the current shell. When you run sudo myfunction then none of this is possible; in particular sudo commands are run as a sub-process and so can't affect the current shell.

The work-around used for things like the sudowrap mentioned above is to try and automatically work out sudo bash -c 'myfunction() {...} ; myfunction'. This explicitly calls a new bash subshell and then runs the function in that subshell. The explicit call makes it clear that things like setting variables and the like won't work :-) It allows for a limited subset of functionality.

The sort of functions you can call this way may be better rewritten as shell scripts rather than functions; then sudo can call them directly. The example given at http://w00tbl0g.blogspot.com/2007/05/using-bash-functions-under-sudo.html would be easier by having duk converted to an executable

#!/bin/bash
exec du -k "$@" | sort -n

That'll then work as expected!