- What is the Windows Subsystem for Linux?
- What is WSL 2?
- Установка WSL
- Предварительные требования
- Установка
- Изменение установленного дистрибутива Linux по умолчанию
- Настройка сведений о пользователе Linux
- Советы и рекомендации
- Хотите испытать новейшие предварительные версии функций WSL?
- Working across Windows and Linux file systems
- File storage and performance across file systems
- View your current directory in Windows File Explorer
- Filename and directory case sensitivity
- Interoperability between Windows and Linux commands
- Run Linux tools from a Windows command line
- Mixing Linux and Windows commands
- Run Windows tools from Linux
- Share environment variables between Windows and WSL with WSLENV
- WSLENV flags
- Disable interoperability
- Install WSL
- Prerequisites
- Install
- Change the default Linux distribution installed
- Set up your Linux user info
- Set up and best practices
- Want to try the latest WSL preview features?
What is the Windows Subsystem for Linux?
The Windows Subsystem for Linux lets developers run a GNU/Linux environment — including most command-line tools, utilities, and applications — directly on Windows, unmodified, without the overhead of a traditional virtual machine or dualboot setup.
- Choose your favorite GNU/Linux distributions from the Microsoft Store.
- Run common command-line tools such as grep , sed , awk , or other ELF-64 binaries.
- Run Bash shell scripts and GNU/Linux command-line applications including:
- Tools: vim, emacs, tmux
- Languages: NodeJS, Javascript, Python, Ruby, C/C++, C# & F#, Rust, Go, etc.
- Services: SSHD, MySQL, Apache, lighttpd, MongoDB, PostgreSQL.
- Install additional software using your own GNU/Linux distribution package manager.
- Invoke Windows applications using a Unix-like command-line shell.
- Invoke GNU/Linux applications on Windows.
What is WSL 2?
WSL 2 is a new version of the Windows Subsystem for Linux architecture that powers the Windows Subsystem for Linux to run ELF64 Linux binaries on Windows. Its primary goals are to increase file system performance, as well as adding full system call compatibility.
This new architecture changes how these Linux binaries interact with Windows and your computer’s hardware, but still provides the same user experience as in WSL 1 (the current widely available version).
Individual Linux distributions can be run with either the WSL 1 or WSL 2 architecture. Each distribution can be upgraded or downgraded at any time and you can run WSL 1 and WSL 2 distributions side by side. WSL 2 uses an entirely new architecture that benefits from running a real Linux kernel.
Источник
Установка WSL
Предварительные требования
Вам следует использовать Windows 10 версии 2004 и выше (сборка 19041 и выше) или Windows 11.
Чтобы проверить версию и номер сборки Windows, нажмите клавиши WINDOWS+R, введите winver и щелкните ОК. Вы можете выполнить обновление до последней версии Windows в меню параметров или с помощью помощника по Центру обновления Windows.
Если вы используете более раннюю сборку или не хотите использовать команду для установки и вам нужны пошаговые инструкции, см. статью Действия по установке WSL вручную для старых версий .
Установка
Теперь вы можете установить все необходимое для запуска подсистемы Windows для Linux (WSL), введя эту команду в PowerShell или командной строке Windows, а затем перезапустив компьютер.
Эта команда позволяет включить необходимые дополнительные компоненты, скачать последнюю версию ядра Linux, установить WSL 2 в качестве компонента по умолчанию и установить дистрибутив Linux (по умолчанию Ubuntu; инструкции по установке другого дистрибутива см. ниже) .
При первом запуске недавно установленного дистрибутива Linux откроется окно консоли. Вам будет предложено подождать, пока файлы будут распакованы и сохранены на компьютере. Все будущие запуски должны занимать меньше секунды.
Изменение установленного дистрибутива Linux по умолчанию
По умолчанию в качестве устанавливаемого дистрибутива Linux используется Ubuntu. Для этого используйте флаг -d .
- Чтобы изменить установленный дистрибутив, введите wsl —install -d . Замените именем дистрибутива, который хотите установить.
- Чтобы просмотреть список доступных дистрибутивов Linux, доступных для скачивания через Интернет-магазин, введите wsl —list —online или wsl -l -o .
- Чтобы установить дополнительные дистрибутивы Linux после исходной установки, можно также использовать команду wsl —install -d .
Если вы хотите установить дополнительные дистрибутивы из командной строки Linux или Bash (а не из PowerShell или командной строки), используйте .exe в команде wsl.exe —install -d . Чтобы получить список доступных дистрибутивов, используйте wsl.exe -l -o .
Если во время установки возникла проблема, см. раздел Установка руководства по устранению неполадок.
Настройка сведений о пользователе Linux
После установки WSL необходимо создать учетную запись пользователя и пароль для установленного дистрибутива Linux. Дополнительные сведения см. в статье Рекомендации по настройке среды разработки WSL.
Советы и рекомендации
Мы рекомендуем использовать наше пошаговое руководство Рекомендации по настройке среды разработки WSL. В нем описано, как настроить имя пользователя и пароль для установленных дистрибутивов Linux, использовать основные команды WSL, установить и настроить Терминал Windows, настроить управление версиями Git, отредактировать код и выполнить отладку с помощью удаленного сервера VS Code. Кроме того, в руководстве приведены рекомендации по хранению файлов, настройке базы данных, подключению внешнего диска, настройке ускорения GPU и пр.
Хотите испытать новейшие предварительные версии функций WSL?
Чтобы поработать с самыми последними функциями или обновлениями для WSL, присоединитесь к Программе предварительной оценки Windows. Когда вы присоединитесь к участникам Программы предварительной оценки Windows, вы сможете выбрать канал для получения предварительных сборок в меню параметров Windows и будете автоматически получать предварительные версии функций и обновления для WSL, связанные с этой сборкой. Можно выбрать одно из следующих значений.
- Канал разработчика: последние обновления, но низкая стабильность.
- Бета-канал: идеально подходит для ранних последователей; более надежные сборки, чем в канале разработки.
- Канал предварительного выпуска: предварительные версии исправлений и основных функций следующей версии Windows непосредственно перед предоставлением их общедоступной версии.
Источник
Working across Windows and Linux file systems
There are a number of considerations to keep in mind when working between Windows and Linux file systems. We have outlined a few of them for you in this guide, including some examples of interoperability support for mixing Windows and Linux-based commands.
File storage and performance across file systems
We recommend against working across operating systems with your files, unless you have a specific reason for doing so. For the fastest performance speed, store your files in the WSL file system if you are working in a Linux command line (Ubuntu, OpenSUSE, etc). If you’re working in a Windows command line (PowerShell, Command Prompt), store your files in the Windows file system.
For example, when storing your WSL project files:
- Use the Linux file system root directory: \\wsl$\Ubuntu-18.04\home\ \Project
- Not the Windows file system root directory: /mnt/c/Users/ /Project$ or C:\Users\ \Project
When you see /mnt/ in the file path of a WSL command line, it means that you are working from a mounted drive. So the Windows file system C:/ drive ( C:\Users\ \Project ) will look like this when mounted in a WSL command line: /mnt/c/Users/ /Project$ . It is possible to store your project files on a mounted drive, but your performance speed will improve if you store them directly on the \\wsl$ drive.
View your current directory in Windows File Explorer
You can view the directory where your files are stored by opening the Windows File Explorer from the command line, using:
Alternatively, you can also use the command: powershell.exe /c start . Be sure to add the period at the end of the command to open the current directory.
To view all of your available Linux distributions and their root file systems in Windows File explorer, in the address bar enter: \\wsl$
Filename and directory case sensitivity
Case sensitivity determines whether uppercase (FOO.txt) and lowercase (foo.txt) letters are handled as distinct (case-sensitive) or equivalent (case-insensitive) in a file name or directory. Windows and Linux file systems handle case sensitivity in different ways — Windows is case-insenstive and Linux is case-sensitive. Learn more about how to adjust case sensitivity, particularly when mounting disks with WSL, in the Adjust case sensitivity how-to article.
Interoperability between Windows and Linux commands
Windows and Linux tools and commands can be used interchangeably with WSL.
- Run Windows tools (ie. notepad.exe) from a Linux command line (ie. Ubuntu).
- Run Linux tools (ie. grep) from a Windows command line (ie. PowerShell).
- Share environment variables between Linux and Windows. (Build 17063+)
Run Linux tools from a Windows command line
Run Linux binaries from the Windows Command Prompt (CMD) or PowerShell using wsl (or wsl.exe ).
Binaries invoked in this way:
- Use the same working directory as the current CMD or PowerShell prompt.
- Run as the WSL default user.
- Have the same Windows administrative rights as the calling process and terminal.
The Linux command following wsl (or wsl.exe ) is handled like any command run in WSL. Things such as sudo, piping, and file redirection work.
Example using sudo to update your default Linux distribution:
Your default Linux distribution user name will be listed after running this command and you will be asked for your password. After entering your password correctly, your distribution will download updates.
Mixing Linux and Windows commands
Here are a few examples of mixing Linux and Windows commands using PowerShell.
To use the Linux command ls -la to list files and the PowerShell command findstr to filter the results for words containing «git», combine the commands:
To use the PowerShell command dir to list files and the Linux command grep to filter the results for words containing «git», combine the commands:
To use the Linux command ls -la to list files and the PowerShell command > out.txt to print that list to a text file named «out.txt», combine the commands:
The commands passed into wsl.exe are forwarded to the WSL process without modification. File paths must be specified in the WSL format.
To use the Linux command ls -la to list files in the /proc/cpuinfo Linux file system path, using PowerShell:
To use the Linux command ls -la to list files in the C:\Program Files Windows file system path, using PowerShell:
Run Windows tools from Linux
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).
- Have the same permission rights as the WSL process.
- Run as the active Windows user.
- Appear in the Windows Task Manager as if directly executed from the CMD prompt.
Windows executables run in WSL are handled similarly to native Linux executables — piping, redirects, and even backgrounding work as expected.
To run the Windows tool ipconfig.exe , use the Linux tool grep to filter the «IPv4» results, and use the Linux tool cut to remove the column fields, from a Linux distribution (for example, Ubuntu) enter:
Let’s try an example mixing Windows and Linux commands. Open your Linux distribution (ie. Ubuntu) and create a text file: touch foo.txt . Now use the Linux command ls -la to list the direct files and their creation details, plus the Windows PowerShell tool findstr.exe to filter the results so only your foo.txt file shows in the results:
Windows tools must include the file extension, match the file case, and be executable. Non-executables including batch scripts. CMD native commands like dir can be run with cmd.exe /C command.
For example, list the contents of your Windows files system C:\ directory, by entering:
Or use the ping command to send an echo request to the microsoft.com website:
Parameters are passed to the Windows binary unmodified. As an example, the following command will open C:\temp\foo.txt in notepad.exe :
This will also work:
Share environment variables between Windows and WSL with WSLENV
WSL and Windows share a special environment variable, WSLENV , created to bridge Windows and Linux distributions running on WSL.
Properties of WSLENV variable:
- It is shared; it exists in both Windows and WSL environments.
- It is a list of environment variables to share between Windows and WSL.
- It can format environment variables to work well in Windows and WSL.
- It can assist in the flow between WSL and Win32.
Prior to 17063, only Windows environment variable that WSL could access was PATH (so you could launch Win32 executables from under WSL). Starting in 17063, WSLENV begins being supported. WSLENV is case sensitive.
WSLENV flags
There are four flags available in WSLENV to influence how the environment variable is translated.
- /p — translates the path between WSL/Linux style paths and Win32 paths.
- /l — indicates the environment variable is a list of paths.
- /u — indicates that this environment variable should only be included when running WSL from Win32.
- /w — indicates that this environment variable should only be included when running Win32 from WSL.
Flags can be combined as needed.
Read more about WSLENV, including FAQs and examples of setting the value of WSLENV to a concatenation of other pre-defined environment vars, each suffixed with a slash followed by flags to specify how the value should be translated and passing variables with a script. This article also includes an example for setting up a dev environment with the Go programming language, configured to share a GOPATH between WSL and Win32.
Disable interoperability
Users may disable the ability to run Windows tools for a single WSL session by running the following command as root:
To re-enable Windows binaries, exit all WSL sessions and re-run bash.exe or run the following command as root:
Disabling interop will not persist between WSL sessions — interop will be enabled again when a new session is launched.
Источник
Install WSL
Prerequisites
You must be running Windows 10 version 2004 and higher (Build 19041 and higher) or Windows 11.
To check your Windows version and build number, select Windows logo key + R, type winver, select OK. You can update to the latest Windows version in the Settings menu or using the Windows Update Assistant.
If you’re running an older build, or just prefer not to use the install command and would like step-by-step directions, see WSL manual installation steps for older versions.
Install
You can now install everything you need to run Windows Subsystem for Linux (WSL) by entering this command in PowerShell or Windows Command Prompt and then restarting your machine.
This command will enable the required optional components, download the latest Linux kernel, set WSL 2 as your default, and install a Linux distribution for you (Ubuntu by default, see below to change this).
The first time you launch a newly installed Linux distribution, a console window will open and you’ll be asked to wait for files to de-compress and be stored on your machine. All future launches should take less than a second.
Change the default Linux distribution installed
By default, the installed Linux distribution will be Ubuntu. This can be changed using the -d flag.
- To change the distribution installed, enter: wsl —install -d . Replace with the name of the distribution you would like to install.
- To see a list of available Linux distributions available for download through the online store, enter: wsl —list —online or wsl -l -o .
- To install additional Linux distributions after the initial install, you may also use the command: wsl —install -d .
If you want to install additional distributions from inside a Linux/Bash command line (rather than from PowerShell or Command Prompt), you must use .exe in the command: wsl.exe —install -d or to list available distributions: wsl.exe -l -o .
If you run into an issue during the install process, check the installation section of the troubleshooting guide.
Set up your Linux user info
Once you have installed WSL, you will need to create a user account and password for your newly installed Linux distribution. See the Best practices for setting up a WSL development environment guide to learn more.
Set up and best practices
We recommend following our Best practices for setting up a WSL development environment guide for a step-by-step walk-through of how to set up a user name and password for your installed Linux distribution(s), using basic WSL commands, installing and customizing Windows Terminal, set up for Git version control, code editing and debugging using the VS Code remote server, good practices for file storage, setting up a database, mounting an external drive, setting up GPU acceleration, and more.
Want to try the latest WSL preview features?
Try the most recent features or updates to WSL by joining the Windows Insiders Program. Once you have joined Windows Insiders, you can choose the channel you would like to receive preview builds from inside the Windows settings menu to automatically receive any WSL updates or preview features associated with that build. You can choose from:
- Dev channel: Most recent updates, but low stability.
- Beta channel: Ideal for early adopters, more reliable builds than the Dev channel.
- Release Preview channel: Preview fixes and key features on the next version of Windows just before its available to the general public.
Источник