How does `alias sudo="sudo "` work?
Asked Answered
L

3

25

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?

Langsyne answered 13/5, 2016 at 12:20 Comment(2)
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.Brigidbrigida
@WilliamPursell, some elaboration on that would be interesting to hear ...Dissentious
H
33

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

Hone answered 13/5, 2016 at 12:24 Comment(0)
V
2

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

Vladikavkaz answered 21/9, 2021 at 10:11 Comment(1)
i +1ed this because its funny and trueCarafe
D
1

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

See https://mcmap.net/q/530531/-how-does-alias-sudo-quot-sudo-quot-work 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
Dear answered 27/7, 2023 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.