Linux home directory windows

Что такое домашний каталог в подсистеме Windows для Linux?

Когда я запускаю bash подсистему Windows для Linux, она бросает меня в каталог

Когда я ls этот каталог, я вижу , каталоги Desktop , Documents и т.д. , которые я могу видеть в C:\Users\ использовании файлов Windows Explorer. Так как именно здесь и началась bash программа, я ожидал, что это мой домашний каталог, но когда я набираю либо, cd либо cd

который содержит мой .bashrc и .profile т. д. файл, который я ожидал найти в своем домашнем каталоге в коробке с Linux. Кроме того, ввод cd ../.. отсюда я могу видеть , каталоги bin , etc и так далее, опять же, как и ожидалось на коробке Linux.

У меня есть два вопроса относительно всего этого:

  1. С чем именно /mnt/c/Users/ сравнивается C:\Users\ ? Кажется, они одно и то же — так что же /mnt/c/ ?
  2. Как я могу просмотреть файлы в /home/ проводнике Windows? Не то, чтобы я действительно этого хотел — я просто пытаюсь понять, как Windows организует эту подсистему для Linux.

Для 2: Текущий путь теперь связан с тем, какой дистрибутив вы установили из Магазина Microsoft, а не с одним глобальным путем. Итак, для Ubuntu он теперь находится по адресу:

Я предполагаю, что другие дистрибутивы будут находиться в аналогичном месте в соответствующих папках под:

  1. /mnt/c точно так же, как C:\ . Это всего лишь синтаксис для получения от него WSL.
  2. Посмотри C:\Users\ \AppData\Local\Lxss\rootfs .

О файловой системе, смонтированной на /mnt/c

  1. Что такое / mnt / c / Users / по сравнению с C: \ Users \? Кажется, они одно и то же — так что же такое / mnt / c /?

В отличие от Windows, Linux (и другие системы, основанные на Unix) используют единую структуру папок, независимо от количества имеющихся у вас дисков. Если у вас есть несколько дисков, все эти диски должны быть в какой-то момент монтированы в структуру папок.

  • Как правило, все диски (отличные от используемых для загрузки системы) монтируются в папку с именем /mnt или /media

WSL имеет специальный тип файловой системы с именем DrvFS, который дает вам доступ к дискам, используемым в Windows. Вы можете использовать DrvFS для монтирования не только файловой системы Windows, но также сетевых дисков и других типов носителей.

  • В WSL по умолчанию C: диск в windows монтируется под /mnt/c
  • Если у вас есть другой диск, например, D: диск в Windows, он будет смонтирован под /mnt/d

Файлы, в которых вы можете видеть, /mnt/c такие же, как у вас C: . Если вы измените какой-либо файл, вы получите изменения и в окнах.

О местонахождении /home/

  1. Как я могу просмотреть файлы в / home / с помощью проводника Windows? Не то, чтобы я действительно этого хотел — я просто пытаюсь понять, как Windows организует эту подсистему для Linux.

В WSL вся файловая система linux находится в папке Windows. Расположение папки зависит от версии Windows и используемого вами дистрибутива WSL.

  • Начальные версии WSL хранят файловую систему Linux в %LOCALAPPDATA%\Lxss\rootfs
  • В дистрибутивах WSL, установленных из Магазина Windows , начиная с Windows Build 16215 (середина 2017 года), используется папка, например %LOCALAPPDATA%\Packages\. \LocalState\rootfs . Название пакета зависит от дистрибутива (например, для Ubuntu оно отличается от Debian)
  • Дистрибутивы Linux, установленные с использованием других инструментов , таких как lxRunOffline или WSL-DistroLauncher, могут хранить файловую систему linux в любом месте.
Читайте также:  Как отключить автозапуск creative cloud mac os

Вы можете проверить множество параметров, чтобы узнать расположение папки WSL . Например, я думаю, что самый простой вариант — использовать lxRunOffline, чтобы узнать папку установки.

Как только вы узнаете, где находится папка установки, она /home/ находится под

Where is /home directory on windows? [duplicate]

How do you find ubuntu’s home directory on windows? I’ve tried searching through windows file explorer by typing ubuntu/home nothing shows up. Does anybody have any suggestions? Thanks for all your help in advance.

4 Answers 4

The equivalent of Ubuntu’s

/ (a.k.a. /home/yourusername/ ) in Windows 10 is C:\Users\yourusername\ .

The equivalent is C:\Users\

So for you, your home directory would be here:

Windows can’t read Linux partitions. That is why you couldn’t find the home directory of Ubuntu.

Instead, you could install third-party softwares to do that, like Ext2Fsd, DiskInternals Linux Reader and so on.

I believe I can safely assume that there is no /home directory on Windows. It probably depends on which Windows OS you are talking about. I think Windows XP, Windows Vista, and Windows 7 has a /home directory, however. In case I am wrong (I probably am) I suggest waiting for another answer.

Not the answer you’re looking for? Browse other questions tagged home-directory or ask your own question.

Linked

Hot Network Questions

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

What is the alternative for

I’m trying to use the command prompt to move some files, I am used to the linux terminal where I use

to specify the my home directory I’ve looked everywhere but I couldn’t seem to find it for windows command prompt ( Documents and Settings\[user] )

11 Answers 11

You’re going to be disappointed: %userprofile%

You can use other terminals, though. Powershell, which I believe you can get on XP and later (and comes preinstalled with Win7), allows you to use

for home directory.

You can %HOMEDRIVE%%HOMEPATH% for the drive + \docs settings\username or \users\username .

You can use %systemdrive%%homepath% environment variable to accomplish this.

The two command variables when concatenated gives you the desired user’s home directory path as below:

Running echo %systemdrive% on command prompt gives:

Running echo %homepath% on command prompt gives:

When used together it becomes:

Update — better version 18th July 2019.

Final summary, even though I’ve moved on to powershell for most windows console work anyway, but I decided to wrap this old cmd issue up, I had to get on a cmd console today, and the lack of this feature really struck me. This one finally works with spaces as well, where my previous answer would fail.

In addition, this one now is also able to use

as a prefix for other home sub-folders too, and it swaps forward-slashes to back-slashes as well. So here it is;

Step 1. Create these doskey macros, somewhere they get picked up every time cmd starts up.

Step 2. Create the cdtilde.bat file and put it somewhere in your PATH

Tested fine with;

Oh, also it allows lazy quoting, which I found useful, even when spaces are in the folder path names, since it wraps all of the arguments as if it was one long string. Which means just an initial quote also works, or completely without quotes also works.

All other stuff below may be ignored now, it is left for historical reasons — so I dont make the same mistakes again

old update 19th Oct 2018.
In case anyone else tried my approach, my original answer below didn’t handle spaces, eg, the following failed.

I think there must be a way to solve that. Will post again if I can improve my answer. (see above, I finally got it all working the way I wanted it to.)

My Original Answer, still needed work. 7th Oct 2018.
I was just trying to do it today, and I think I got it, this is what I think works well;

Читайте также:  Драйвер для принтера canon lbp 3200 для windows

First, some doskey macros;

What is the home directory on Windows Subsystem for Linux?

When I start bash on Windows Subsystem for Linux, it drops me in the directory

When I ls this directory, I see the directories Desktop , Documents , etc. that I can see are in C:\Users\ using the Windows File Explorer. Since this is where the bash program started, I expected this is my home directory, but when I type either cd or cd

I am brought to

which contains my .bashrc , .profile etc. file which I would expect to find in my home directory in a Linux box. Moreover, entering cd ../.. from here I can see the directories bin , etc and so on, again as expected on a Linux box.

I have two questions regarding all this:

  1. What exactly is /mnt/c/Users/ compared with C:\Users\ ? It seems they are one in the same—so what is /mnt/c/ ?
  2. How can I view the files in /home/ using the Windows File Explorer? Not that I’d really ever want to—I’m just trying to get a feel for how Windows is organizing this Subsystem for Linux thing.

11 Answers 11

In the latest versions [2020], the file system is accessed from:

Previously, as of 2018, The current path is related to which distribution you have installed from the Microsoft Store rather than one global path; for Ubuntu, it was located at:

Other distributions should be (to be confirmed) in a similar location under their respective folders within:

In Bash, to view the current directory in Windows File Explorer just enter:

Don’t leave out the «.».

This will open windows explorer at the current folder and you can see where everything is in relation to the rest of your Windows system.

  1. /mnt/c is the exact same as C:\ . It’s just the syntax for getting to it from WSL.
  2. Look in C:\Users\ \AppData\Local\Lxss\rootfs .

About the filesystem mounted on /mnt/c

  1. What exactly is /mnt/c/Users/ compared with C:\Users ? It seems they are one in the same—so what is /mnt/c/?

In contrast to Windows, Linux (and the other systems based on Unix) use a single folder structure independent of the number of disks you have. If you have multiple disks, all these disks must me mounted into the folder structure at some point.

  • Typically, all the disks (different than the used to boot the system) are mounted in a folder named /mnt or /media

WSL has an special type of filesystem named DrvFS that gives you access to the disks used in windows. You can use DrvFS to mount, not only your windows filesystem, but also network disks and other media types.

  • In WSL, by default, the C: disk in windows is mounted under /mnt/c
  • If you have another disk, for instance a D: disk in windows, it will be mounted under /mnt/d

The files you can see in /mnt/c are the same you have in C: . If you modify some file, you will get the changes in the windows too.

About the location of /home/

  1. How can I view the files in /home/ using the Windows File Explorer? Not that I’d really ever want to—I’m just trying to get a feel for how Windows is organizing this Subsystem for Linux thing.

In WSL, all the linux filesystem is located under a Windows folder. The location of the folder depends on the version of Windows and of the WSL distribution you are using.

  • Initial versions of WSL store the linux filesystem in %LOCALAPPDATA%\Lxss\rootfs
  • WSL distributions installed from the Windows Store, starting in Windows Build 16215 (mid of 2017), use a folder like %LOCALAPPDATA%\Packages\\LocalState\rootfs . The name of the package varies depending on the distribution (e.g. it is different for Ubuntu than for Debian). For Ubuntu on Windows it is CanonicalGroupLimited.UbuntuonWindows_ , for example.
  • Linux distributions installed using other tools, such as lxRunOffline or WSL-DistroLauncher may store the linux filesystem into any location.

You may check many options to know the location of the WSL folder. For instance, I think the easiest option is to use lxRunOffline to know the installation folder.

Once you know the location of the installation folder, the /home/ is under \rootfs\home\username .

  • For instance, if your installation folder is c:\wsl\ubuntu
  • the /home/ is in c:\wsl\ubuntu\rootfs\home\username

NOTE: Both Linux and Windows stores file permissions in different ways. Nowadays, the WSL DrvFS stores the Linux permissions as Streams (metadata) attached to the files you can see in Windows. Microsoft does not recommend to modify linux files using Windows programs. It is possible that some Windows applcations damage the linux permissions without notice it.

Крутые лайфхаки для работы с WSL (Подсистема Windows для Linux )

Я глубоко погружен в 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, вот так.

Исполняемые файлы 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.

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

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

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

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

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

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

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

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

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

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

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

Оцените статью