24

Looking at ways to pass current user's aliases to a sudo command, I found the following on ArchWiki:

Passing aliases

If you use a lot of aliases, you might have noticed that they do not carry over to the root account when using sudo. However, there is an easy way to make them work. Simply add the following to your ~/.bashrc or /etc/bash.bashrc:

alias sudo='sudo '

I don't get why this works. If the shell does not care how many spaces are between two commands, how can this have any effect?

When manually adding a space, I see no difference:

$ alias e=echo
$ sudo e foo
sudo: e: command not found
$ sudo  e foo              # Manual space addition
sudo: e: command not found # Fail
$ alias sudo="sudo "       # Now with alias
$ sudo e foo
foo                        # Succeeds, but why?

Visibly aliasing sudo to sudo + space somehow allows passing aliases. This works on zsh, bash and sh, so it is not a shell-specific behavior.

How does this alias work?

1
  • 5
    This is not something to understand, just don't do it. Allowing sudo to invoke an alias is about as good an idea as standing on a rickety three legged stool with a noose around your neck. May 13, 2016 at 13:07

3 Answers 3

32

Looking at the man page for alias:

A trailing space in VALUE causes the next word to be checked for alias substitution when the alias is expanded.

Source: http://www.linuxcommand.org/lc3_man_pages/aliash.html

1

The trailing space makes the shell try alias expansion on the next word as well.

See https://stackoverflow.com/a/37210013/2115619 for source.

This can be nested indefinitely:

alias e1=echo e2='echo ' b='extreme mega beans to the max'
e1 b
#> b
e2 b
#> extreme mega beans to the max
e2 e2 e2 b
#> echo echo extreme mega beans to the max
e2 e2 e1 b
#> echo echo b
e2 e1 e2 b
#> echo e2 b
e1 e2 e2 b
#> e2 e2 b

You can also make a useless but transparent alias like this:

alias echo='echo ' expand=' '
echo expand expand expand expand expand expand expand expand expand meow
#> meow
0

What we got in best practices for the team:

alias sodu='sudo'
alias sodo='sudo'
alias sdoo='sudo'
alias sudu='sudo'
alias sduo='sudo'

Just add an alias you think is necessary for yourself

1

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.