Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `alias sudo="sudo "` work?

Tags:

alias

shell

sh

sudo

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?

like image 214
PLNech Avatar asked May 13 '16 12:05

PLNech


1 Answers

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

like image 187
Andreas Louv Avatar answered Oct 25 '22 17:10

Andreas Louv