2023年3月1日星期三

Change default user of WSL1&2

Recently, I moved my WSL Ubuntu distribution out of my C drive due to insufficient disk space.

After the "export-import" operation, my default login user for WSL changed to root.

Normally, as a virtual environment, it shouldn't bother me at all. However, my Python packages are installed under a normal user account, which was the default login user.

I tried to find the /etc/wsl.conf file but failed, so I decided to do a small trick to save time.

 Append following code to /root/.bashrc.

PP_NAME=`ps -p $PPID -o comm=`
#echo "PP_NAME: $PP_NAME"
if [ "$PP_NAME" == "init" ]
then
    su <YOUR_USERNAME>
    exit
fi

But it only works when we start wsl from cmd. VSCode's wsl will still start with root user.

Thus, we still need to use the /etc/wsl.conf .

If there is no /etc/wsl.conf, then create it. And fill the file with:

[user] default=username

If you are using WSL 1, just close all your WSL instances. And restart WSL.

If you are using WSL 2, you need to use 'wsl --shutdown' command to stop your WSL2 VM first, then restart your  WSL.