[英]bash alias using sudo returning command not found
I am trying to use the solution of using sudo on my existing aliases as covered in many existing answers already and i am so confused as to why it is not working我正在尝试使用在我现有的别名上使用 sudo 的解决方案,正如许多现有答案中所涵盖的那样,我很困惑为什么它不起作用
alias sudo='sudo '
I keep all my aliases in .bash_aliases
.我将所有别名保存在
.bash_aliases
中。 Inside .bash_aliases
I have this在
.bash_aliases
里面我有这个
function _test {
echo 'test!'
}
alias test='_test'
I reload the.bashrc each time;我每次都重新加载.bashrc;
source.bashrc
but when I run sudo test
I always get source.bashrc
但是当我运行sudo test
我总是得到
sudo: _test: command not found
sudo:_test:找不到命令
The only strange thing that happens is that I get the following on reload and not on a new terminal发生的唯一奇怪的事情是我在重新加载而不是在新终端上得到以下内容
dircolors: /home/MYHOME/.dircolors: No such file or directory
dircolors: /home/MYHOME/.dircolors: 没有这样的文件或目录
but i feel this is a red herring.但我觉得这是一个红鲱鱼。
To run an alias like alias_name
it must be exactly the first word in the command, so sudo alias_name
will never work.要运行像
alias_name
这样的别名,它必须恰好是命令中的第一个单词,因此sudo alias_name
永远不会起作用。 Ditto 'alias_name'
, \alias_name
and other things which eventually expand to the alias name.同上
'alias_name'
, \alias_name
和其他最终扩展为别名的东西。
As l0b0 says , aliases cannot be used in this way in bash.正如 l0b0 所说,在 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).但是,您可以通过 function 传递(实际上,基本上没有充分的理由使用别名而不是单独使用函数)。
_test() {
echo 'test!'
}
sudo_test() {
sudo bash -c "$(declare -f _test)"'; _test "$@"' sudo_test "$@"
}
...will define a command sudo_test
that runs the function _test
via sudo
. ...将定义一个命令
sudo_test
通过sudo
运行 function _test
。 (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). (如果您的 function 的实际版本调用其他函数或需要访问 shell 变量,请将这些其他函数添加到
declare -f
命令行,和/或在同一命令替换中添加declare -p
以生成文本描述function 需要的变量)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.