更新时间:2023-11-19 19:33:10
正如 l0b0 所说,别名不能 在 bash 中以这种方式使用.
As l0b0 says, aliases cannot be used in this way in bash.
但是,您可以传递一个函数(实际上,基本上从来没有一个很好的理由使用别名而不是单独使用函数).
However, you can pass a function through (and really, there's basically never a good reason to use an alias instead of sticking to functions alone).
_test() {
echo 'test!'
}
sudo_test() {
sudo bash -c "$(declare -f _test)"'; _test "$@"' sudo_test "$@"
}
...将定义一个命令 sudo_test
,它通过 sudo
运行函数 _test
.(如果此函数的实际版本调用其他函数或需要访问 shell 变量,请将这些其他函数添加到 declare -f
命令行,和/或添加 declare -p
在同一个命令替换中,以生成函数所需变量的文本描述).
...will define a command sudo_test
that runs the function _test
via sudo
. (If your real-world version of this function calls other functions or requires access to shell variables, add those other functions to the declare -f
command line, and/or add a declare -p
inside the same command substitution to generate a textual description of variables your function needs).