Why doesn't $HOME change if I use sudo?
I expected the -H option to give me the target user's environment.
nbest@geo:~$ sudo -H -u tanum echo $HOME /home/nbest nbest@geo:~$ sudo -u tanum echo $HOME /home/nbest nbest@geo:~$ sudo -i -u tanum echo $HOME /home/nbest nbest@geo:~$ sudo -H -i -u tanum echo $HOME /home/nbest
This would allow me to say:
sudo -u tanum ls ~
and get the target user's home directory listing. Not the case. Is this caused by the env_reset
default in sudoers
?
If so does -H have any effect? What is the safest way to override this behavior?
If not what is the intended effect of -H?
Please set me straight.
Solution 1:
$HOME
and ~
get expanded by your shell, they are not interpreted by echo
.
In other words, echo
does not see $HOME
as an argument. It actually sees /home/nbest
. Therefore the following commands are exactly identical (in your case):
nbest@geo:~$ sudo -H -u tanum echo $HOME
nbest@geo:~$ sudo -H -u tanum echo /home/nbest
Whatever you try (-H
, -i
, ...) you will never obtain the wanted behavior. Because $HOME
is replaced by your shell and your shell runs as your user. sudo
does not affect your shell in any way.
To work around this 'issue' (which actually is a feature), you can start a new subshell:
nbest@geo:~$ sudo -H -u tanum sh -c 'echo $HOME'
(Note that I'm using single quotes to avoid expansion.) This way, the new shell sh
will run as user tanum and print his home directory.
An another alternative is to use ~username
, which gets expanded to the home of that user, without the need of using sudo
or su
. Try:
nbest@geo:~$ echo ~tanum
Solution 2:
Please try:
sudo -H -u tanum bash -c 'echo $HOME'