Reputation: 23
Question would be
what exactly is the difference between running these two commands.
As a root, I have made a custom env. variable
export A="abcdef"
then in root shell
sudo -i
echo $A
returns
abcdef (as expected)
However, when I go back to normal user and run
sudo -i echo $A
it returns blank line.
So when you run command sudo echo $A, does it use environment variables and shell from the normal user?
and is there a way to get abcdef even if I run sudo echo $A ?
Thanks
EDIT 1
When you say you have made a variable A as root, I assume you mean you did this in root's .profile or something like that. --> (yes!)
EDIT 2
This makes perfect sense but having some trouble.
When I do
sudo -i 'echo $A'
I get
-bash: echo $A: command not found.
However when I do
su -c 'echo $A'
it gives back
abcdef
What is wrong with the
sudo -i 'echo $A'
command?
Upvotes: 2
Views: 4612
Reputation: 299325
When you say you have made a variable A
as root, I assume you mean you did this in root's .profile or something like that. And I assume you mean that the normal user does not have A
set. In that case the following applies:
When you run your command sudo -i echo $A
this is first interpreted by the local shell and $A
is substituted. That results in sudo -i echo
, which is what is actually executed.
What you mean is this:
sudo -i 'echo $A'
That passes echo $A
to the sudo shell.
~ rnapier$ sudo -i echo $USER
rnapier
~ rnapier$ sudo -i 'echo $USER'
root
Try this syntax:
sudo -i echo '$USER'
Upvotes: 2
Reputation: 3638
If you want to pass your environment to sudo
, use sudo -E
:
-E The -E (preserve environment) option indicates to the
security policy that the user wishes to preserve their
existing environment variables. The security policy may
return an error if the -E option is specified and the user
does not have permission to preserve the environment.
The environment is preserved both interactively and through whatever you run from the command line.
Upvotes: 4
Reputation: 775
Although I couldn't replicate the results on my machine, the man page for sudo, specifies the -i option will unset/remove a handful of variables.
man sudo
-i [command]
The -i (simulate initial login) option runs the shell specified in the passwd(5) entry of the target user as a login shell. This means that login-specific resource files such as .profile or .login will be read by the shell. If a command is specified, it is passed to the shell for execution. Otherwise, an interactive shell is executed. sudo attempts to change to that user's home directory before running the shell. It also initializes the environment, leaving DISPLAY and TERM unchanged, setting HOME , MAIL , SHELL , USER , LOGNAME , and PATH , as well as the contents of /etc/environment on Linux and AIX systems. All other environment variables are removed.
So I would try without the -i option.
Upvotes: 0