Why does "sudo -u root echo `whoami`" not return root?

Solution 1:

sudo echo `whoami` 

Returns your name because whoami changes to your username before sudo runs. It's like:

sudo echo myname

you can see tese codes:

myname@mypc:~$ whoami
myname

myname@mypc:~$ sudo whoami
root

myname@mypc:~$ echo `whoami`
myname

myname@mypc:~$ sudo echo `whoami`
myname

myname@mypc:~$ sudo `echo whoami`
root

myname@mypc:~$ sudo -i
[sudo] Password for myname: ******

root@mypc:~$ whoami
root

root@mypc:~$ echo `whoami`
root

Thanks

Solution 2:

In fact it does run them as root. But, what's happening to you is that the back ticks are being evaluated before sudo runs, as they're needed to evaluate the command. More directly, why not just this:

sudo whoami

Your whoami in back ticks is actually evaluated in a subshell as the current user, which is why you see what you do.

Solution 3:

The subshell (whoami) is executed first, as you, and the result (myuser) is placed into the sudo command; what sudo sees is echo myuser. Think of it as a shortcut for:

tmpvar=`whoami`
sudo echo "$tmpvar"

Solution 4:

There seems to be some surmising going on here…

The backticks are obviously doing what others explained, expanding whoami before invoking 'sudo', and leaving the backticks off return 'root', as expected.

But it's useful to understand what is actually happening with sudo(8). So I actually looked at the man page!

"The real and effective uid and gid are set to match those of the target user…"

So it appears that the observed behaviour has nothing to do with the difference between effective and real user id.

It's also illustrative to do "sudo printenv" and compare to just "printenv," which actually surprised me a bit. It shows that [i]some[/i] exported variables are available and and others are not: it reports the invoking user's HOME, PATH, PS1, SHELL, TERM, and EDITOR, but not others like MANPATH, CVSROOT, LD_LIBRARY_PATH, or ENV. That seems a bit odd, as it could cause programs to behave differently than they do either as the original user, or as root.