- Как работать с Linux используя Windows
- Ubuntu из Microsoft Store
- VirtualBox
- Do not change Linux files using Windows apps and tools
- Update – May 2019 Windows 10 version 1903 has now been released and allows an important update to WSL that allows Windows applications and tools to access Linux files directly. To do this, WSL hosts a new 9P fileserver, which exposes distro filesystems to Windows apps and tools via \wsl$\ \ ! You can read all about the feature in the blog post “What’s new for WSL in Windows 10 version 1903“.
- DO NOT, under ANY circumstances , access, create, and/or modify Linux files inside of your `%LOCALAPPDATA%` folder using Windows apps, tools, scripts, consoles, etc.
- Creating/changing Linux files in your Appdata folder from Windows will likely result in data corruption and/or damage your Linux environment requiring you to uninstall & reinstall your distro!
- What SHOULD I do?
- Why is this?
- Access Linux filesystems in Windows and WSL 2
- Getting started
- Accessing these files with File Explorer
- Limitations
- Give us your feedback!
Как работать с Linux используя Windows
Инструкция по установке Ubuntu Linux внутри Windows с использованием различных технологий виртуализации.
Содержание
Если вы только начали свой путь разработчика и до сих используете операционную систему семейства Microsoft Windows, то уже наверняка столкнулись с ситуацией, когда ваш инструментарий отличается от того, что установлено у большинства людей из этой профессии. Чаще всего проблемы начинаются при работе в командной строке. Дело в том, что Windows не является POSIX-совместимой операционной системой, поэтому в ней отсутсвует базовый набор прикладных программ, который необходим для разработки.
Этот вопрос можно решить установкой какого-либо из многочисленных дистрибутивов Linux в качестве основной, либо альтернативной операционной системы. Для новичков есть способ проще и быстрее — технологии виртуализации. Об этом и поговорим.
Ubuntu из Microsoft Store
Если вы работаете на Windows версии 10 с архитектурой x64, то можно можно воспользоваться встроенным решением и установить слой совместимости (Windows Subsystem for Linux) на основе Ubuntu Linux через магазин приложений Microsoft Store.
Перед тем как начать, необходимо убедиться, что системные требования соответствуют рекомендованным. Для этого запустите приложение Microsoft Store, введите в графе поиска Ubuntu и перейдите по найденной ссылке. Если ранее Windows не обновлялся, то вероятней всего вы получите соответствующее указание сделать это до начала установки Ubuntu. Если всё OK, то нажимайте на кнопку «Получить» и через несколько минут (в зависимости от скорости интернет соединения) вы получите сигнал об успешной установке приложения.
Первый запуск может вызвать ошибку Error: 0x8007007e и предложение прочитать инструкцию по её решению https://aka.ms/wslinstall. Если хотите сэкономить время, то просто запустите PowerShell (не путать с cmd ) от имени администратора и выполните следующую команду:
После этого компьютер попросит перегрузиться, а потом нужно снова запустить приложение Ubuntu. В случае удачной установки откроется интерпретатор командной строки с предложением ввести имя пользователя и пароль. Выглядеть это будет вот так:
Преимущество такого способа установки позволяют стереть грань между операционными системами и получить доступ ко всему инструментарию Linux ( bash , ssh , git , apt и так далее) из стандартной командной строки Windows не теряя привычное окружение и оставаясь на одном файловом уровне.
Ссылки на официальную документацию:
VirtualBox
Если вы работаете на Windows версии ниже 10 или хотите получить изолированную операционную систему Linux, да ещё и с графическим окружением, то можно воспользоваться сторонним бесплатным программным продуктом под названием VirtualBox.
Инсталлятор Oracle VM VirtualBox для Windows Hosts
Ссылка на скачивание: Download Oracle VM VirtualBox
Образ операционной системы Ubuntu Linux в формате ISO
Ссылка на скачивание: Download Ubuntu Desktop
Для начала необходимо установить и запустить приложение VirtualBox.
Нажимаем кнопку «Создать», выбираем из списка тип операционной системы «Linux», если нет своих предпочтений по дистрибутиву, то выбираем версию «Ubuntu» 32 или 64 битной архитектуры, а название можно ввести любое.
Указываем объём оперативной памяти выделенной под виртуальную систему. Рекомендованный объём составляет 1024 MB.
Указываем объём дискового пространства выделенного под виртуальную систему. Рекомендованный объём составляет 10 GB.
Тип виртуального жёсткого диска можно оставить как есть — VDI (VitrualBox Disk Image).
Формат хранения данных выберите исходя из личных предпочтений. Динамический виртуальный жёсткий диск растёт по мере заполнения, а фиксированный создаётся сразу того размера, который был указан на предыдущем шаге.
Имя и размер файла можно оставить без изменений и сразу нажать на кнопку «Создать».
По завершению у вас будет создана виртуальная машина, но она пока без операционной системы. Для того чтобы её установить, нужно скачать Ubuntu Linux (32-bit или 64-bit, в зависимости от того, что было выбрано на шаге, где мы указывали тип ОС).
Нажатие на кнопку «Запустить» должно привести к появлению диалогового окна с предложением указать путь до скаченного ISO образа. Сделайте этого и нажмите кнопку «Продолжить»
Виртуальная машина автоматически будет выполнять часть процессов, но в некоторых операциях всё же потребуется участие пользователя.
Выберите языковую поддержку в списке слева и нажмите «Установить Ubuntu».
Можно загрузить обновления сразу на этапе установки.
Без особых опасений выбираем пункт «Стереть диск и установить Ubuntu» и двигаемся дальше.
Если вы выбрали русский язык на первом этапе установки, то вам предложат русскую раскладку клавиатуры в качестве дополнительной.
Заполните поля и выберите режим входа в систему.
Далее начнётся процедура разметки диска, переноса файлов, установка обновлений и другие процессы, которые не потребуют прямого участия пользователя.
По завершению виртуальный компьютер перезагрузится и вы попадёте в уже установленную среду Ubuntu Linux.
Но это ещё не всё. Весьма желательно установить так называемые «Дополнения гостевой ОС». Они содержат драйверы и прочие системные файлы, необходимые для наилучшей производительности и обеспечения дополнительных функциональных возможностей между виртуальной и гостевой операционными системами.
Выберите пункт меню «Устройства» программы VitrualBox, подпункт «Подключить образ диска Дополнений гостевой ОС…» и дождитесь предложение запустить приложение для автоматического запуска с виртуального привода.
Виртуальная ОС Ubuntu Linux установлена и готова к работе.
Ссылка на официальную документацию: Oracle VM VirtualBox User Manual
Do not change Linux files using Windows apps and tools
November 17th, 2016
Update – May 2019 Windows 10 version 1903 has now been released and allows an important update to WSL that allows Windows applications and tools to access Linux files directly. To do this, WSL hosts a new 9P fileserver, which exposes distro filesystems to Windows apps and tools via \\wsl$\ \ ! You can read all about the feature in the blog post “What’s new for WSL in Windows 10 version 1903“.
The post below contains the original guidance, which also remains true: DO NOT access the Linux files inside of your %LOCALAPPDATA% folder, since you should only be accessing them . If you’d like to learn more about why you shouldn’t go digging through the Appdata folder for your Linux files, please read on!
There is one hard-and-fast rule when it comes to WSL on Windows:
DO NOT, under ANY circumstances , access, create, and/or modify Linux files inside of your `%LOCALAPPDATA%` folder using Windows apps, tools, scripts, consoles, etc.
Opening > files using some Windows tools may read-lock the opened files > and/or folders, preventing updates to file contents and/or metadata, > essentially resulting in corrupted files/folders.
Creating/changing Linux files in your Appdata folder from Windows will likely result in data corruption and/or damage your Linux environment requiring you to uninstall & reinstall your distro!
Note: In beta versions of WSL, your “Linux files” are any of the files and folders under %localappdata%\lxss – which is where the Linux filesystem – distro and your own files – are stored on your drive. In supported versions of WSL, the filesystems for the distros you install via the Microsoft Store are stored elsewhere on disk … for good reason!
What SHOULD I do?
To work on files using both Windows and Linux tools, store files in your Windows filesystem – this will enable you to access the same files from both Windows and from your Linux distros via /mnt/ /
When you access files on your Windows filesystem from within Bash, WSL honors the NT filesystem behaviors (e.g. case-insensitivity), permissions, etc. so you can easily access the same files using both Windows tools and Bash tools without having to copy files back and forth between filesystems.
Therefore, be sure to follow these three rules in order to avoid losing files, and/or corrupting your data:
- DO store files in your Windows filesystem that you want to access/create/modify using Windows tools AND Linux tools
- DO access / create / modify files in your Linux distros’ filesystems from Windows apps, tools, scripts or consoles using \\wsl$\ \
DO NOT access / create / modify files in your Linux distros’ filesystems from Windows apps, tools, scripts or consoles by finding the files in Appdata
Remember: There’s a reason we store your distros’ filesystems in non-obvious locations!
Why is this?
File metadata (e.g. permissions, ownership, timestamps, etc.) is stored for every file, folder, etc., on your storage devices. Alas, file metadata representation differs from one OS to another: Windows file metadata is different from Linux file metadata.
While it’s the OS’ job to store and update your file metadata, most of Windows doesn’t know anything about Linux, nor Linux file metadata, and doesn’t automatically add or update Linux file metadata for all Windows files because that would impose an unnecessary overhead on the vast majority of Windows users who will never run WSL.
It’s WSL’s job to write/update Linux file metadata for all the files under your Linux filesystem root (i.e. /), storing the Linux metadata in each file’s NTFS extended attributes. WSL also synthesizes pseudo metadata for most of the files in your Windows filesystem.
The problem arises when, for example, you use a Windows app/tool to open, create and/or modify a file under your distro root: Since the file was created with a Windows tool, the file won’t have any Linux file metadata (e.g. permissions, owner, access/update timestamps, etc.). Thus, to Linux, (which only receives Linux file metadata), the file may be reported as empty, may not even exist, or may have some metadata, but that metadata may not reflect the file’s details resulted in the file’s contents being corrupted.
Further, as in Linux, some Windows tools implement unusual filesystem access patterns to handle file updating and don’t actually edit files in-place: When apps/tools save changes to a file, the original files are often deleted and re-created, etc. During such operations, NT file “extended properties” (i.e. Linux file permissions) are often not copied and are “lost”.
For more background into how the WSL filesystem infrastructure works, be sure to read/watch this AWESOME blog & video which explains things in much more detail.
Please help us share this guidance far and wide – tweet, post and blog, linking back to this post!!
- [2017-03-14] – Updated “Why is this”; thanks to @mn in comments
- [2019-01-15] – Minor updates & improvements
- Last Updated: [2019-05-29] – Added an edit to the top of the post to describe the new feature allowing users to access Linux files from Windows
Access Linux filesystems in Windows and WSL 2
September 10th, 2020
Starting with Windows Insiders preview build 20211, WSL 2 will be offering a new feature: wsl —mount . This new parameter allows a physical disk to be attached and mounted inside WSL 2, which enables you to access filesystems that aren’t natively supported by Windows (such as ext4).
So, if you’re dual booting with Windows & Linux using different disks, you can now access your Linux files from Windows!
Getting started
To mount a disk, open a PowerShell window with administrator privileges and run:
To list the available disks in Windows, run:
To unmount and detach the disk from WSL 2, run
The disks paths are available under the ‘DeviceID’ columns. Usually under the \\.\\\.\PHYSICALDRIVE* format. Below is an example of mounting a specific partition of a given hard disk into WSL and browsing its files.
Accessing these files with File Explorer
Once mounted, it’s also possible to access these disks through the Windows explorer by navigating to \wsl$ and then to the mount folder.
Limitations
By default, wsl —mount attempts to mount the disk as ext4. To specify a filesystem, or for more advanced scenarios, check out Mount a disk in WSL 2.
Also please note that this feature comes with the limitation that only physical disks can be attached to WSL 2. At this time, it’s not possible to attach a single partition. More details on the limitations here.
Give us your feedback!
If you run into any issues, or have feedback for our team please file an issue on our Github , and if you have general questions about WSL you can find all of our team members that are on Twitter on this twitter list.