1

I have two Ubuntu VM's where one is running on VirtualBox (Ubuntu 18.04) and the other is on WSL 1 (Ubuntu 20.04).

#!/bin/bash

dir=~
echo $dir

When I run the above shell script without the sudo, both VM's print my own /home/user directory. But when run this with sudo, VirtualBox instance prints /home/user and the WSL instance prints /root. I'm not sure why this happens and if there is any relevance to VM's.

I need this to print the /home/user directory in the WSL instance even when running as sudo. I achieved this by running this as sudo -E but I don't know if that's the best method. Can someone explain why do I get different behaviours in different environments?

  • 1
    Related: [How is sudo set to not change $HOME in Ubuntu and how to disable this behavior?](https://unix.stackexchange.com/questions/91384/how-is-sudo-set-to-not-change-home-in-ubuntu-and-how-to-disable-this-behavior) – steeldriver Aug 21 '21 at 19:43
  • 1
    Regarding the difference in behavior between the environments - Is there any chance the VirtualBox VM is running 18.04? On my 18.04 instances, I see `$HOME`/`$HOME`, regardless of whether it's WSL or on my "pure Linux" 18.04 machine. On my 20.04 WSL instances and my 20.04 "real Linux" hosts, I see `$HOME`/`/root`. Not sure what changed between the two releases to cause this (yet), though. – NotTheDr01ds Aug 21 '21 at 20:24
  • You can consider making use of the env var `SUDO_USER` as well but of course it won't be as "generic" as env keeping. – Tom Yan Aug 21 '21 at 20:25
  • 1
    @NotTheDr01ds the "old" behaviour (pre-19.04 iirc) was the result of an Ubuntu-specific patch I think - see [How do Ubuntu and Debian manage $HOME for users with sudo privileges?](https://unix.stackexchange.com/questions/438564/how-do-ubuntu-and-debian-manage-home-for-users-with-sudo-privileges) – steeldriver Aug 21 '21 at 20:27
  • @steeldriver Now that you mention it, I recall coming across that when investigating some `sudoers` options a couple of years ago. Thanks! – NotTheDr01ds Aug 21 '21 at 20:44
  • @NotTheDr01ds Yes exactly. Ubuntu version in VirtualBox is 18.04 and WSL is 20.04. So it seems like this is related to Ubuntu versions I guess. – Amila Abeygunasekara Aug 21 '21 at 20:47
  • Yes, and per @steeldriver's comment, it's a difference in `sudoers` that causes this. Updating the `sudoers` (via `visudo`) in the 18.04 versions to match the `env_keep`/`env_reset`/`always_set_home`/`set_home` settings from 20.04 should smooth things out. – NotTheDr01ds Aug 21 '21 at 21:59

0 Answers0