Как из wsl получить доступ к файлам windows

Cover image for Access the Windows file system through WSL!

Have you ever wondered, how to access the windows file system through WSL? If the answer is yes you are in the right place!

Microsoft WSL has given us an incredible way to access the windows file system, you have just to navigate through an exact path to do it. Without further due, let’s dive into the topic.

1. Use the cd command in the Linux terminal.

To access the windows files you have to navigate through /mnt/your_windows_path

cd /mnt/c/Users
**OR**
cd /mnt/d/your_folder/your_folder

Enter fullscreen mode

Exit fullscreen mode

Now you have access to every file in the Linux and Windows file systems.

2. Moving files between the two systems through WSL.

If you want to move files between the two operating systems you can simply use the cp or mv commands.
cp — command for copying files
mv — command for moving files
Use of cp command

cp /mnt/c/file.txt /home/username/Documents

Enter fullscreen mode

Exit fullscreen mode

Use of mv command

mv  /mnt/c/file.txt /home/username/Documents

Enter fullscreen mode

Exit fullscreen mode

3. Editing windows files through WSL.

To edit windows files through the Linux terminal using WSL, you have to use any text editor that can be opened in the terminal. One of the most famous text editors is nano. In our example, I am going to use the nano editor.
Type into the terminal nano and the path to the file.

sudo nano /mnt/c/Users/file.txt

Enter fullscreen mode

Exit fullscreen mode

Now you can edit freely files from your terminal.

4. Creating files in windows through WSL.

To create a file in a specific windows directory you have first to navigate to it and then use the touch command to create a file.
touch — a command that creates a file.
!!! The file extension can be anything you want.

cd /mnt/c/Users/Public/Documents/ 
touch filename.txt

Enter fullscreen mode

Exit fullscreen mode

The file is created and can be opened from both systems.

5. Deleting files from the windows file system through WSL.

To delete windows files using WSL, you have to navigate to the directory where the file lives and use the rm command.
rm — a command that deletes files / directories

cd /mnt/c/Users/Public
sudo rm example_file.jpg

Enter fullscreen mode

Exit fullscreen mode

Congratulations you learned 5 vital skills about working with the Linux terminal. 🎺🎺🎺
If you have any questions, comment down, I will answer as soon as possible.

I’m starting to learn how to use the terminal with Ubuntu on WSL (Windows).

Just from the very beginning of the course it says that if you use the ls command it should show you your «home» directories, but mine is something like this:

(base) paloma@DESKTOP-ISCC0ON:~$ ls
Anaconda3-2021.11-Linux-x86_64.sh  anaconda3

(base) paloma@DESKTOP-ISCC0ON:~$

And if I try to change directory something like this happens:

(base) paloma@DESKTOP-ISCC0ON:~$ ls
Anaconda3-2021.11-Linux-x86_64.sh  anaconda3

(base) paloma@DESKTOP-ISCC0ON:~$ cd Documents
-bash: cd: Documents: No such file or directory

(base) paloma@DESKTOP-ISCC0ON:~$

Can somebody tell me why is this happening and what can I do, please? I’m a complete newbie.

NotTheDr01ds's user avatar

NotTheDr01ds

15.8k6 gold badges52 silver badges80 bronze badges

asked Nov 23, 2022 at 11:47

Paloma's user avatar

Everything in @Tooster’s answer is corrected, but let me address your main question a bit more directly:

(base) paloma@DESKTOP-ISCC0ON:~$ cd Documents
-bash: cd: Documents: No such file or directory

Can somebody tell me why is this happening and what can I do, please?

You appear to be wondering why this isn’t taking you to the Documents folder in your Windows home directory.

It’s important to understand that the home directory in Ubuntu/WSL is not the same as your Windows home directory, nor should it be. Your Ubuntu home directory is in a virtual SSD provided by WSL. This virtual SSD provides the Linux compatible filesystem that Ubuntu needs, whereas your Windows drive is formatted as NTFS and won’t have 100% compatibility.

WSL does provide a way to get to the Windows files (including your home directory), as mentioned by @Tooster.

From inside Ubuntu:

cd /mnt/c/Users/<your_Windows_username>
ls

That should show you all the files and directories in your Windows profile (a.k.a. home) folder.

Also perhaps reading as additional background — My answer to Where is WSL located on my computer?.

answered Nov 28, 2022 at 2:29

NotTheDr01ds's user avatar

NotTheDr01dsNotTheDr01ds

15.8k6 gold badges52 silver badges80 bronze badges

First of all try to format code and output from terminals using the fenced code block format.

And now to the meritum.

  • current working directory is the directory you are in. Your home directory (often denoted with ~) is usually located in the /home/<username>/
  • ls — command listing files in the current directory
  • ls [arguments...] — this command lists the files inside directories provided as arguments
  • cd [argument] — change directory command. using it without argument takes you to your home directory
  • / is root directory in linux and an absolute paths start with it
  • . is a current directory and if path starts with ./something or without it something, then current directory is assumed (path is relative to current location)
  • .. is parent directory.

Based on the (base) in thee prompt and on the names of the files above, I’m gonna say that you are using conda environment on your WSL (Windows subsystem for linux). Why are you using it is not my business, but you seem to have skipped a few steps when learning linux and WSL first. Try starting with https://linuxjourney.com/ (especially command line section and filesystem section). Then learn about differences in linux and windows structure.


@EDIT because I only noticed you are using Linux on Windows

Because linux’ and windows’ filesystems are a bit different, when you start linux on windows a virtual filesystem is created for you. To access your windows files from linux you would have to access /mnt/<drive>/<...windows files> (note the / at the beginning — that’s an absolute path)

Linux is structured as a single tree rooted at / and external filesystems are usually mounted at /mnt (read hier(7) for more info). Windows’ filesystem is composed of «drives» — single trees rooted at C:/, D:/ etc., so it’s only natural for both of those systems to have different mechanism for accessing each other’s files.

Read more at https://ling123labs.com/posts/WSL-files-in-Windows-and-vice-versa/

answered Nov 23, 2022 at 12:21

Tooster's user avatar

ToosterTooster

4372 silver badges13 bronze badges

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Время на прочтение
3 мин

Количество просмотров 38K

Я глубоко погружен в WSL (Windows Subsystem для Linux), и теперь, когда WSL2 доступен в Windows Insiders, это отличное время, чтобы по-настоящему изучить доступные опции. Очень интересная фича, которую я нашел в WSL, — возможность «чисто» перемещать данные между мирами. Это не тот опыт, который вы легко можете получить с полноценными виртуальными машинами, и он говорит о тесной интеграции Linux и Windows.

Под катом подробнее о некоторых интересных вещах, которые вы можете делать, смешивая арахисовое масло и шоколад!

Запустите Windows Explorer из Linux и получите доступ к файлам вашего дистрибутива

Когда вы находитесь в командной строке WSL / bash и хотите получить визуальный доступ к своим файлам, вы можете запустить «explorer.exe .», где находится текущий каталог, и вы получите окно проводника Windows, в котором ваши файлы Linux будут доставлены вам через сервер локальной сети plan9.

Используйте настоящие команды Linux (не CGYWIN) из Windows

Я уже писал об этом раньше, но теперь есть алиасы для функций PowerShell, которые позволяют вам использовать настоящие команды Linux изнутри Windows.

Вы можете вызвать любую команду Linux напрямую из DOS/Windows/чего угодно, просто поместив ее после WSL.exe, вот так.

C:\temp> wsl ls -la | findstr "foo"
-rwxrwxrwx 1 root root     14 Sep 27 14:26 foo.bat

C:\temp> dir | wsl grep foo
09/27/2016  02:26 PM                14 foo.bat

C:\temp> wsl ls -la > out.txt

C:\temp> wsl ls -la /proc/cpuinfo
-r--r--r-- 1 root root 0 Sep 28 11:28 /proc/cpuinfo

C:\temp> wsl ls -la "/mnt/c/Program Files"
...contents of C:\Program Files...

Исполняемые файлы Windows можно вызывать/запускать из WSL/Linux, поскольку путь к Windows находится в $PATH до Windows. Все, что вам нужно сделать, это явно вызвать его с .exe в конце. Вот как работает «Explorer.exe.». Вы также можете сделать notepad.exe или любой другой файл.

Запустите Visual Studio Code и получите доступ к вашим приложениям Linux нативно на Windows

Вы можете запустить «code.», находясь в папке в WSL, и вам будет предложено установить расширения VS Remote.. Это эффективно разделяет Visual Studio Code пополам и запускает «headless» VS Code Server в Linux с клиентом VS Code в мире Windows.

Вам также необходимо установить Visual Studio Code и расширение Remote — WSL. При желании, установите бета-версию Windows Terminal для лучшего опыта работы с терминалом в Windows.

Вот отличная подборка статей из блога Windows Command Line.

  • Часть 1 Поднимите опыт разработки Linux под Windows на новый уровень с помощью WSL и Visual Studio Code Remote.
  • Часть 2 Углубленное руководство по разработке Linux для Windows с WSL и Visual Studio Code
  • Часть 3 Советы и рекомендации по разработке Linux с использованием WSL и Visual Studio Code

Вот преимущества WSL 2

  • Виртуальные машины являются ресурсоемкими и создают очень независимый опыт.
  • Исходный WSL был очень «подключенным», но имел довольно низкую производительность по сравнению с VM.
  • WSL 2 предлагает гибридный подход с облегченными VM, полностью подключенным интерфейсом и высокой производительностью.

Запуск нескольких Linux в считанные секунды

Здесь я использую «wsl —list —all», и в моей системе уже есть три Linux.

C:\Users\scott>wsl --list --all
Windows Subsystem for Linux Distributions:
Ubuntu-18.04 (Default)
Ubuntu-16.04
Pengwin

Я могу легко запустить их, а также назначить профили, чтобы они появлялись в моем Windows Terminal.

Запустите X Windows Server под Windows с Pengwin

Pengwin — это специальный Linux-дистрибутив WSL, который очень крут. Вы можете получить его в Windows Store. Объедините Pengwin с X Server, например X410, и вы получите очень классную интегрированную систему.

Простое перемещение дистрибутивов WSL между системами Windows.

Ana Betts отмечает эту замечательную технику, с помощью которой вы можете легко перенести свой идеальный дистрибутив WSL2 с одной машины на n машин.

wsl --export MyDistro ./distro.tar

# разместите его где-нибудь, Dropbox, Onedrive, где-то еще

mkdir ~/AppData/Local/MyDistro
wsl --import MyDistro ~/AppData/Local/MyDistro ./distro.tar --version 2 

Вот и все. Получите идеальную настройку Linux, синхронизированную на всех ваших системах.

Используйте провайдер учетных данных Windows Git внутри WSL

Все перечисленные фичи переткают в кульминацию в этом крутом посте от Ana Betts, где она интегрирует Windows Git Credential Provider в WSL, превращая /usr/bin/git-credential-manager в сценарий оболочки, который вызывает диспетчер git creds Windows. Гениально. Это было бы возможно только при условии чистой и тесной интеграции.

Пробуйте, устанавливайте WSL, Windows Terminal, и создавайте блестящую среду Linux на Windows..

I’ve been getting a few questions from Windows users about accessing WSL files in Windows and vice versa. I was originally going to wait with this for the next labs, but since this might actually make things a little clearer for some, I’ll just post the information here instead. If anything’s unclear, just wait for the second lab and I’ll probably be able to explain things better in person.


The WSL distributables (i.e. Ubuntu) are kind of like another machine running within your computer. It just features a Unix command-line interface (that’s the terminal, i.e. the bash shell), so the development tools and experiences are pretty limited. You can run vim, nano, or even emacs (might need to be installed) in the terminal to edit your files, but if you want to use a full-fledged IDE you’ll normally have to edit the files on the Windows side and then transfer them over to the Linux environment in WSL.

When we start working with Python, R and jflap, you can probably just solve the exercises on Windows, since you don’t need Linux to write Python or R code. Of course, you can always install python3 in Ubuntu, but you won’t have access to an IDE (unless you follow the guide in the last part of this post).

Accessing your WSL files in Windows

If you are using WSL 1, this should probably work fine most of the time. However, if you are using WSL2, it probably won’t. WSL2 doesn’t like it when we edit files in both Linux WSL and in Windows. WSL1 doesn’t like it either, but it’s possible to do, and I’ve tried so myself many times now without issues.

To access your Linux files in Windows, open the Ubuntu terminal and type explorer.exe . (include the punctuation mark). This will open the linux directory in Windows Explorer, with the WSL prefix “\wsl$\Ubuntu-18.04\home\your-username”.

Now, you’ll notice that Windows treats your Linux environment as a second network. This is because, as I’ve stated earlier, the Linux environment is completely separate from the Windows environment and transferring files between these environments is very similar to transferring files between computer networks. I always recommend that you copy the file you want over to a Windows folder before editing it, so that you won’t mess up the original if the file gets corrupted.

PS: To copy the file, run cp [filename] [destination], like this: console cp file.txt /backup/new_file.txt

Accessing your Windows files in the WSL terminal

Similarly, you can also open your Windows files in the Linux environment. Just use the cd command to navigate to your WSL root folder, then navigate into the mnt folder to access your C: drive. See the example below for more details. As you can see, I managed to access my Documents folder. Make sure to enter your own username when you try this yourself.

Accessing your Windows files in WSL

I recommend you to use the cp command to copy the files you need from Windows to your Linux environment, so that if anything should get corrupted you’re not going to mess up the original file.

Working in WSL with VScode

VScode is a full-fledged IDE from Microsoft, which has very recently released support for editing Linux files remotely. This means that you can open VScode from the Ubuntu terminal, run it in Windows, but edit the files in Linux while also being able to access the Linux terminal and viewing pathnames and home directory correctly. I’ve tried it out today, and… it just works!

So if you insist on using an IDE to edit your Linux files directly, even though you won’t really need to in this course, you can do it by installing the Remote — WSL extension for VScode. See the documentation and guides here.

VSCode WSL-remote demo VScode editor with WSL-remote enabled

Download Windows Speedup Tool to fix errors and make PC run faster

Microsoft added the support for Windows Subsystem for Linux (WSL) on Windows 11 and Windows 10. It made it possible for users to install various Linux distros like Ubuntu, SUSE Linux, Kali Linux and more on Windows 10 devices. Not only is WSL getting a real Kernel, but the ability to access Linux files on Windows 11/10 using File Explorer will also be present.

Access Windows Subsystem for Linux files on Windows 10

There are two methods to access Windows Subsystem for Linux files using File Explorer on Windows 11/10:

  1. Opening File Explorer from the WSL Terminal.
  2. Launching the root from File Explorer.

1] Using File Explorer inside WSL Terminal

Access Windows Subsystem for Linux files on Windows 10

  1. Open WSL terminal.
  2. Navigate the root directory or top folder inside of the Terminal.
  3. Type in explorer.exe and hit Enter to open that location inside of the File Explorer.

2] Launching the root from File Explorer

This is a relatively straightforward method.

  1. Launch the File Explorer.
  2. Type in Linux and hit Enter in the address bar of the File Explorer.
  3. It will mount the storage for the Linux distros installed on your computer.
  4. The files are visible in File Explorer.

After you access these files within File Explorer, you can use programs installed on your computer to execute them normally. And any modification that you make will be visible inside the Terminal window.

Can you access Windows files from Linux subsystem?

Yes, you can access Windows files from the Linux subsystem and vice versa. It is possible to share and access Windows files from the Linux subsystem using the WSL terminal. You need to open the File Explorer in the terminal. In other words, you can enter the explorer.exe command in the terminal window to get access to it.

Read: An error occurred mounting one of your file systems WSL error

Where are the Linux subsystem files on Windows 11/10?

To access the Linux subsystem files or Linux Bash files on Windows 11/10, you need to go to %userprofile%\AppData\Local\Packages. Alternatively, you can go to C:\Users\user-name\AppData\Local\Packages in the File Explorer. However, you must show hidden files to access the AppData folder in the C drive or system drive.

WSL has proven to be a boon for all the developers who had to dual boot a Linux flavor to get their needs with the Terminal done.

Troubleshoot: Windows Subsystem for Linux Error Messages and Codes.

Ayush has been a Windows enthusiast since the day he got his first PC with Windows 98SE. He is an active Windows Insider since Day 1 and has been a Windows Insider MVP.

  • Как избавиться от ой в яндексе windows 10
  • Как из windows увидеть раздел linux
  • Как играть в ex machina на windows 10
  • Как из windows увидеть разделы linux
  • Как избавиться от обновлений windows 10 навсегда