2

I'd like to understand bash better and when variables are evaluated.

When using sudo the user environment that can be checked out using env is exchanged with the root environment. Hence env and sudo env yield different results.

Now if I am doing sudo echo "I am $USER"! the result is I am my-username! instead of I am root!, presumably because the $USER variable is looked up before the sudo command is excuted.

How can I use that same command so that I am root! is printed? Do I need some switches or change the string somehow?

jaaq
  • 1,188
  • 11
  • 29
  • You need to switch user use `sudo su - root` or something equivalent. If you do sudo env you'll see the environment variables being set – bob dylan Mar 09 '20 at 12:29

1 Answers1

7

In the command sudo echo "$USER", bash evaluates $USER first and then executes the command. In that case your username is printed.

If you want to print the root username, the parameter expansion must be done as the root user. It can be done using bash -c command:

sudo bash -c 'echo "$USER"'
oliv
  • 12,690
  • 25
  • 45
  • Huh, I tried `sudo /bin/bash -c "echo I am $USER!"` and gave up there, but apparently both your solution AND `sudo /bin/bash -c 'echo I am $USER!'` work. I never thought to try if maybe double quotes do interpolation and single quotes don't [which is indeed the case](https://stackoverflow.com/a/6697781/6301103). Just didn't know what to look for. Thanks for the answer! – jaaq Mar 10 '20 at 11:43