My take on this, built upon other answers, but as far as I can see the only one properly handling function arguments and quoting:
sudo-function() {
(($#)) || { echo "Usage: sudo-function FUNC [ARGS...]" >&2; return 1; }
sudo bash -c "$(declare -f "$1");$(printf ' %q' "$@")"
}
$ args() { local i=0; while (($#)); do echo "$((++i))=$1"; shift; done; }
$ sudo-function args a 'b c' "d 'e'" 'f "g"'
1=a
2=b c
3=d 'e'
4=f "g"
And expanding it to also run on aliases, builtins, and executables in user's but not root's $PATH:
super-sudo() {
(($#)) || { echo "Usage: super-sudo CMD [ARGS...]" >&2; return 1; }
local def ftype; ftype=$(type -t $1) ||
{ echo "not found: $1" >&2; return 1; }
if [[ "$ftype" == "function" ]]; then def=$(declare -f "$1")
else def=$(declare -p PATH); fi # file or builtin
sudo bash -c "${def};$(printf ' %q' "$@")"
}
alias super-sudo='super-sudo ' # so it runs aliases too
As most (all?) answers, it has a few limitations:
- Does not work if FUNC calls other functions
- As
sudo, it might not work as expected if mixed with redirections and process substitutions<>>,<(), etc.
And a small bonus: bash-completion!
complete -A function sudo-function
complete -c super-sudo