Reputation: 9838
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.
Upvotes: 1
Views: 1923
Reputation: 295500
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).
Upvotes: 1
Reputation: 58848
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.
Upvotes: 0