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?
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"'