Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing existing Windows environment variables from WSL

I would like to access existing Windows environment variables such as USERPROFILE from withing the WSL bash prompt. There is information from Microsoft on the use of WSLENV here, and I have tried to work with this:

I added WSLENV as a new System variable within the usual Windows "Environment Variables" control panel, setting it to USERPROFILE/u. I then open Ubuntu from the taskbar, and type:

$ echo $USERPROFILE

...but nothing is returned.

like image 806
user2023370 Avatar asked Feb 01 '18 16:02

user2023370


People also ask

How do I access Windows folder from WSL?

From within WSL Way back with Windows 10 version 1903 (May 2019), Microsoft added some options to access your files in WSL far more easily. Whenever you are in a directory in WSL that you would like to access from File Explorer, simply type: $ explorer.exe . $ explorer.exe .

Can WSL access Windows processes?

One of the benefits of WSL is being able to access your files via both Windows and Linux apps or tools. Using your mounted drives, you can edit code in, for example, C:\dev\myproj\ using Visual Studio / or VS Code, and build/test that code in Linux by accessing the same files via /mnt/c/dev/myproj .

Can WSL run Windows commands?

WSL can run Windows tools directly from the WSL command line using [tool-name].exe . For example, notepad.exe . Applications run this way have the following properties: Retain the working directory as the WSL command prompt (for the most part -- exceptions are explained below).


1 Answers

Improved Gábor's answer, since as I've discovered it had a small bug, variables obtained that way contain invisible carriage return character, that could cause unexpected issues latter. Here is Example:

$ cd /mnt/c/
$ mkdir Windows_NT
$ tmpvar=`/mnt/c/Windows/System32/cmd.exe /C "echo %OS%"`
$ echo $tmpvar
Windows_NT

All seems to be ok, but no:

$ cd $tmpvar
: No such file or directory

This is because tmpvar variable contains additional carriage return character (aka ^M or \r) at the end. We can check this via ls command:

$ ls -ld $tmpvar
ls: cannot access 'Windows_NT'$'\r': No such file or directory

In order to remove that character, output could be be additionally processed with sed or tr:

tmpvar=$(cmd.exe /C echo %OS%|sed $'s/\r$//')

or

tmpvar=$(cmd.exe /C echo %OS%|tr -d '\r')

I've also simplified command a bit. Path /mnt/c/Windows/System32 is already included in $PATH WSL variable by default in recent Windows 10 updates, so just cmd.exe should work.

Now, ls and cd commands work without errors:

$ ls -ld $tmpvar
drwxrwxrwx 1 ubuntu ubuntu 512 Feb 12 05:38 Windows_NT
$ cd $tmpvar
$ pwd
/mnt/c/Windows_NT

pwd command confirms that current directory is correct.

like image 58
Dmitry Avatar answered Sep 24 '22 00:09

Dmitry