Both Debian and Ubuntu ship an /etc/sudoers
file that contains Defaults env_reset
, which resets environment variables.
However, the behavior of env_reset
was changed from not touching $HOME
to resetting it to the home of the target user.
In releases up to 19.04, Ubuntu had patched their version of sudo
to keep the previous behavior (of not changing $HOME
):
https://bugs.launchpad.net/ubuntu/+source/sudo/+bug/760140
This was undone for 19.10, and starting since, Ubuntu does what upstream sudo
and all other Linux distributions do, and changes $HOME
to that of the target user. See this Q&A on askubuntu.com for all the details: How does sudo handle $HOME differently since 19.10?. The reversal was not done for earlier releases, so 18.04 LTS still has the Ubuntu-specific behaviour.
The following is the old text of this answer, and applies to Ubuntu releases up to 19.04, including 18.04 LTS.
In Ubuntu, in order to reset the $HOME environment variable to the target user, one has to set either Defaults always_set_home
or Defaults set_home
(in which case only sudo -s
will get HOME updated) in their /etc/sudoers
.
This bug at Ubuntu tracker has some more rationale on not setting $HOME in sudo:
https://bugs.launchpad.net/ubuntu/+source/sudo/+bug/1373495
See comment #4:
If HOME is removed, then e.g. vim, bash, etc., will use /root/.vimrc,
/root/.bashrc, etc rather than the user's ~/.vimrc, ~/.bashrc, etc.
While it's a bad idea to run X clients via sudo, they too would likely
look in the wrong locations for configuration files, and there's a
chance that X11 clients may not even be able to connect to the X11
server if they are aimed at the wrong .Xauthority file.
It's a conscious decision by Ubuntu developers.
This answer has more details on the sudoers options such as always_set_home
:
https://unix.stackexchange.com/a/91572/281844
There's a second issue in your question, which is the sudo echo $HOME
which still displays the user's home even in Debian.
That happens because the shell is expanding $HOME
before running the sudo
command.
So this:
$ sudo echo $HOME
Is first expanded by the shell into:
$ sudo echo /home/user
And then sudo executes echo /home/user
as root...
This should demonstrate the difference too:
$ sudo bash -c 'echo $HOME'
/root
Or get a full root shell and see the environment variable there:
$ sudo -s
# echo $HOME
/root