简体   繁体   中英

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

alias sudo='sudo '

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

function _test {
    echo 'test!'
}

alias test='_test'

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

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: No such file or directory

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. Ditto 'alias_name' , \alias_name and other things which eventually expand to the alias name.

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 "$@"
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM