Manipulating Files between a WSL Instance and Host Machine

Photo by Jr Korpa on Unsplash

Manipulating Files between a WSL Instance and Host Machine

·

2 min read

Although WSL (Windows Subsystem for Linux) changed the game for developing on Windows, I inevitably will come across pain points in my workflow. One issue I frequently encountered was manipulating files between the host machine's drives and a WSL instance.

Manipulating files within a WSL instance

Let's say we have a file named alice.txt located on a Windows drive with the file address of C:\Users\<WIN_USER_NAME>\Documents\. To move the file to a WSL instance to the present working directory, run the following in a WSL terminal instance:

mv /mnt/c/Users/<WIN_USER_NAME>/Documents/ .

Note how they are essentially the same file path with just two key differences! First, /mnt prepends any file address. Second, backslashes (\) are swapped for slashes (/). Now that we know this, we can easily leverage other file manipulation commands, such as ls, cp, cat, vi, file, and so on.

Manipulating files in a WSL instance from Windows

Let's say we have the same file as before, alice.txt, but we've moved it to the WSL instance and it now has the file path of /home/<WSL_USER_NAME>/. To manipulate this file from your Windows host machine, the most straightforward way is to simply use File Explorer and navigate to \\wsl$.

Here you'll see a folder for each of your WSL instances, where the folder names should map to the Linux distro that each instance uses (e.g. Ubuntu). Likely, you'll only have a single WSL instance so it should be simple to locate the correct folder. Navigate into the WSL instance folder, then home, and finally <WSL_USER_NAME>. Congrats, you'll find alice.txt in this folder and can manipulate it accordingly!

You can even leverage the knowledge of these file addresses for CMD or PowerShell commands. To quickly check the current file address, simply right-click on the File Explorer address bar at the top and click "Edit Address" to display the file address in place or "Copy Address as Text" to copy the file address to your clipboard.

Did you find this article valuable?

Support Neil Patel by becoming a sponsor. Any amount is appreciated!