找不到使用 sudo 返回命令的 bash 别名 [英] bash alias using sudo returning command not found

查看:40
本文介绍了找不到使用 sudo 返回命令的 bash 别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用在我现有的别名上使用 sudo 的解决方案,正如许多现有答案中已经涵盖的那样,我很困惑为什么它不起作用

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

alias sudo='sudo '

我将所有别名保存在 .bash_aliases 中.在 .bash_aliases 里面我有这个

I keep all my aliases in .bash_aliases. Inside .bash_aliases I have this

function _test {
    echo 'test!'
}

alias test='_test'

我每次都重新加载 .bashrc;source .bashrc 但是当我运行 sudo test 我总是得到

I reload the .bashrc each time; source .bashrc but when I run sudo test I always get

sudo: _test: 命令未找到

sudo: _test: command not found

发生的唯一奇怪的事情是我在重新加载而不是在新终端上得到以下内容

The only strange thing that happens is that I get the following on reload and not on a new terminal

dircolors:/home/MYHOME/.dircolors: 没有那个文件或目录

dircolors: /home/MYHOME/.dircolors: No such file or directory

但我觉得这是一个红鲱鱼.

but i feel this is a red herring.

推荐答案

正如 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).

这篇关于找不到使用 sudo 返回命令的 bash 别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆