- Взаимодействие Windows с Linux Windows interoperability with Linux
- Запуск инструментов Linux из командной строки Windows Run Linux tools from a Windows command line
- Смешивание команд Linux и Windows Mixing Linux and Windows commands
- Запуск инструментов Windows из Linux Run Windows tools from Linux
- Совместное использование переменных среды между Windows и WSL Share environment variables between Windows and WSL
- Флаги WSLENV WSLENV flags
- Отключение взаимодействия Disable interoperability
- Предшествующие версии Windows 10 Earlier versions of Windows 10
Взаимодействие Windows с Linux Windows interoperability with Linux
В подсистеме Windows для Linux (WSL) постоянно улучшается интеграция между Windows и Linux. The Windows Subsystem for Linux (WSL) is continuously improving integration between Windows and Linux. Можно сделать следующее. You can:
- Запустить средства Windows (например, notepad.exe) из командной строки Linux (например, Ubuntu). Run Windows tools (ie. notepad.exe) from a Linux command line (ie. Ubuntu).
- Запустить средства Linux (например, grep) из командной строки Windows (например, PowerShell). Run Linux tools (ie. grep) from a Windows command line (ie. PowerShell).
- Совместное использование переменных среды между Linux и Windows. Share environment variables between Linux and Windows. (сборка 17063+) (Build 17063+)
Если вы используете Creators Update (октябрь 2017 г., сборка 16299) или Юбилейное обновление (август 2016 г., сборка 14393), перейдите к более ранним версиям Windows 10. If you’re running Creators Update (Oct 2017, Build 16299) or Anniversary Update (Aug 2016, Build 14393), jump to the Earlier versions of Windows 10.
Запуск инструментов Linux из командной строки Windows Run Linux tools from a Windows command line
Запускайте двоичные файлы Linux из командной строки Windows (CMD или PowerShell), используя wsl (или wsl.exe ). Run Linux binaries from the Windows Command Prompt (CMD) or PowerShell using wsl (or wsl.exe ).
Например: For example:
Двоичные файлы вызываются следующим образом. Binaries invoked in this way:
- Используется тот же рабочий каталог, что и для текущей командной строки или сеанса PowerShell. Use the same working directory as the current CMD or PowerShell prompt.
- Файл выполняется от имени пользователя WSL по умолчанию. Run as the WSL default user.
- Требуются те же права администратора Windows, что и у вызывающего процесса и терминала. Have the same Windows administrative rights as the calling process and terminal.
Команда Linux после wsl (или wsl.exe ) обрабатывается как любая команда, выполняемая в WSL. The Linux command following wsl (or wsl.exe ) is handled like any command run in WSL. Можно выполнять sudo, конвейерную передачу и перенаправление файлов. Things such as sudo, piping, and file redirection work.
Пример использования sudo для обновления дистрибутива Linux по умолчанию: Example using sudo to update your default Linux distribution:
Имя пользователя дистрибутива Linux по умолчанию будет указано после выполнения этой команды, и вам будет предложено указать пароль. 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.
Смешивание команд Linux и Windows Mixing Linux and Windows commands
Ниже приведено несколько примеров смешиваний команд Linux и Windows с помощью PowerShell. Here are a few examples of mixing Linux and Windows commands using PowerShell.
Чтобы выполнить команду Linux ls -la для вывода списка файлов и команду PowerShell findstr для фильтрации результатов слов, содержащих git, объедините команды: 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:
Чтобы выполнить команду PowerShell dir для вывода списка файлов и команду Linux grep для фильтрации результатов слов, содержащих git, объедините команды: 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:
Чтобы использовать команду Linux ls -la для вывода списка файлов и команду PowerShell > out.txt для вывода этого списка в текстовый файл с именем out.txt, объедините команды: 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:
Команды, передаваемые в wsl.exe , перенаправляются в процесс WSL без изменения. The commands passed into wsl.exe are forwarded to the WSL process without modification. Пути к файлам должны быть указаны в формате WSL. File paths must be specified in the WSL format.
Чтобы выполнить команду Linux ls -la для вывода списка файлов в пути файловой системы Linux /proc/cpuinfo с помощью PowerShell, сделайте следующее: To use the Linux command ls -la to list files in the /proc/cpuinfo Linux file system path, using PowerShell:
Чтобы выполнить команду Linux ls -la для вывода списка файлов в пути файловой системы Windows C:\Program Files с помощью PowerShell, сделайте следующее: To use the Linux command ls -la to list files in the C:\Program Files Windows file system path, using PowerShell:
Запуск инструментов Windows из Linux Run Windows tools from Linux
WSL может запускать средства Windows непосредственно из командной строки WSL с помощью [tool-name].exe . WSL can run Windows tools directly from the WSL command line using [tool-name].exe . Например, notepad.exe . For example, notepad.exe .
\’` as the file path.» Currently it I can just enter `notepad.exe foo.txt` and it seems to work fine, so explaining a situation where the file path is needed would be helpful. —>
Приложения, выполняемые таким образом, обладают следующими свойствами. Applications run this way have the following properties:
- Рабочим каталогом остается каталог командной строки WSL (в большинстве случаев; исключения описаны ниже). Retain the working directory as the WSL command prompt (for the most part — exceptions are explained below).
- Они имеют те же разрешения, что и процесс WSL. Have the same permission rights as the WSL process.
- Они выполняются от имени активного пользователя Windows. Run as the active Windows user.
- Они отображаются в диспетчере задач Windows так, как если бы они выполнялись непосредственно из командной строки. Appear in the Windows Task Manager as if directly executed from the CMD prompt.
Исполняемые файлы Windows, выполняемые в WSL, обрабатываются аналогично собственным исполняемым файлам Linux — конвейерной передаче, перенаправлению и даже фоновому режиму работы. Windows executables run in WSL are handled similarly to native Linux executables — piping, redirects, and even backgrounding work as expected.
Чтобы запустить средство Windows ipconfig.exe , использовать средство Linux grep для фильтрации результатов IPv4, а также средство Linux cut для удаления полей столбцов из дистрибутива Linux (например, Ubuntu), введите: 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:
Давайте рассмотрим пример сочетания команд Windows и Linux. Let’s try an example mixing Windows and Linux commands. Откройте дистрибутив Linux (например, Ubuntu) и создайте текстовый файл: touch foo.txt . Open your Linux distribution (ie. Ubuntu) and create a text file: touch foo.txt . Теперь используйте команду Linux ls -la , чтобы отобразить список файлов прямого доступа и сведения об их создании, а также средство Windows PowerShell findstr.exe , чтобы отфильтровать результаты и отобразить только файл 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 должны иметь расширение файла, его регистр символов должен совпадать с регистром в имени файла и эти файлы должны быть исполняемыми. Windows tools must include the file extension, match the file case, and be executable. Неисполняемые файлы, в том числе сценарии пакетного выполнения и Non-executables including batch scripts. собственные команды командной строки, такие как dir , можно выполнять с помощью команды cmd.exe /C . CMD native commands like dir can be run with cmd.exe /C command.
Например, отобразите список содержимого каталога C:\ файловой системы Windows, введя: For example, list the contents of your Windows files system C:\ directory, by entering:
Или выполните команду ping , чтобы отправить запрос проверки связи на веб-сайт microsoft.com: Or use the ping command to send an echo request to the microsoft.com website:
Параметры передаются в двоичный файл Windows без изменений. Parameters are passed to the Windows binary unmodified. Например, следующая команда откроет C:\temp\foo.txt в notepad.exe . As an example, the following command will open C:\temp\foo.txt in notepad.exe :
Этот способ также будет работать: This will also work:
Совместное использование переменных среды между Windows и WSL Share environment variables between Windows and WSL
Решение WSL и Windows совместно используют WSLENV — специальную переменную среды, созданную для взаимодействия Windows и дистрибутивов Linux, запущенных в WSL. WSL and Windows share a special environment variable, WSLENV , created to bridge Windows and Linux distributions running on WSL.
Свойства переменной WSLENV : Properties of WSLENV variable:
- она используется совместно и существует в средах Windows и WSL; It is shared; it exists in both Windows and WSL environments.
- это список переменных среды, которые совместно используют Windows и WSL; It is a list of environment variables to share between Windows and WSL.
- она позволяет форматировать список переменных среды для корректного использования в Windows и WSL. It can format environment variables to work well in Windows and WSL.
- она может использоваться в потоке между WSL и Win32. It can assist in the flow between WSL and Win32.
До выпуска сборки 17063 единственной переменной среды Windows,, к которой могла получить доступ WSL, была PATH (это позволяло запускать исполняемые файлы Win32 из WSL). Prior to 17063, only Windows environment variable that WSL could access was PATH (so you could launch Win32 executables from under WSL). Начиная со сборки 17063, WSLENV поддерживается. Starting in 17063, WSLENV begins being supported. WSLENV учитывает регистр. WSLENV is case sensitive.
Флаги WSLENV WSLENV flags
В WSLENV доступны четыре флага, влияющие на способ преобразования переменной среды. There are four flags available in WSLENV to influence how the environment variable is translated.
Флаги WSLENV : WSLENV flags:
- /p преобразовывает пути WSL и Linux в пути Win32 и наоборот; /p — translates the path between WSL/Linux style paths and Win32 paths.
- /l указывает, что переменная среды представляет собой список путей; /l — indicates the environment variable is a list of paths.
- /u указывает, что эту переменную среды следует добавлять только при запуске WSL из Win32; /u — indicates that this environment variable should only be included when running WSL from Win32.
- /w указывает, что эту переменную среды следует добавлять только при запуске Win32 из WSL. /w — indicates that this environment variable should only be included when running Win32 from WSL.
При необходимости флаги можно комбинировать. Flags can be combined as needed.
Узнайте больше о WSLENV, ознакомившись с часто задаваемыми вопросами и примерами установки значения WSLENV для объединения других предварительно определенных переменных среды с суффиксом в виде косой чертой и флагами для указания способа перевода значения и передачи переменных скрипту. 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. В этой статье также показано, как настроить среду разработки с помощью языка программирования Go для совместного использования GOPATH с WSL и Win32. 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
Пользователи могут отключить возможность запуска средств Windows для отдельного сеанса WSL, выполнив следующую команду в качестве привилегированного пользователя. Users may disable the ability to run Windows tools for a single WSL session by running the following command as root:
Чтобы повторно включить возможность запуска двоичных файлов Windows, закройте все сеансы WSL и повторно запустите bash.exe или выполните следующую команду от имени привилегированного пользователя. To re-enable Windows binaries, exit all WSL sessions and re-run bash.exe or run the following command as root:
Отключение взаимодействия не будет сохраняться между сеансами WSL, оно снова будет включено при запуске нового сеанса. Disabling interop will not persist between WSL sessions — interop will be enabled again when a new session is launched.
Предшествующие версии Windows 10 Earlier versions of Windows 10
В предшествующих версиях Windows 10 для команд взаимодействия существует несколько различий. There are several differences for the interoperability commands on earlier Windows 10 versions. Если вы используете версию Creators Update (октябрь 2017 г., сборка 16299) или Юбилейного обновления (август 2016 г., сборка 14393) Windows 10, мы рекомендуем выполнить обновление до последней версии Windows. Если это невозможно, мы выделили некоторые отличия при взаимодействии ниже. If you’re running a Creators Update (Oct 2017, Build 16299), or Anniversary Update (Aug 2016, Build 14393) version of Windows 10, we recommend you update to the latest Windows version, but if that’s not possible, we have outlined some of the interop differences below.
- bash.exe заменен на wsl.exe ; bash.exe has been replaced with wsl.exe .
- параметр -c не требуется для выполнения одной команды wsl.exe ; -c option for running a single command isn’t needed with wsl.exe .
- путь Windows включен в переменную $PATH WSL. Windows path is included in the WSL $PATH .
- Процесс отключения взаимодействия не изменяется. The process for disabling interop is unchanged.
Команды Linux можно запускать из командной строки Windows или из PowerShell, но для ранних версий Windows необходимо использовать команду bash . Linux commands can be run from the Windows Command Prompt or from PowerShell, but for early Windows versions, you man need to use the bash command. Например: For example:
Такие функции, как ввод, конвейерная передача и перенаправление файлов, работают должным образом. Things such as input, piping, and file redirection work as expected.
Команды WSL, передаваемые в bash -c , перенаправляются в процесс WSL без изменения. The WSL commands passed into bash -c are forwarded to the WSL process without modification. Пути к файлам должны быть указаны в формате WSL, кроме того, необходимо внимательно экранировать соответствующие знаки. File paths must be specified in the WSL format and care must be taken to escape relevant characters. Пример: Example:
При вызове средства Windows из дистрибутива WSL в ранних версиях Windows 10 необходимо указать путь к каталогу. When calling a Windows tool from a WSL distribution in an earlier version of Windows 10, you will need to specify the directory path. Например, в командной строке WSL введите: For example, from your WSL command line, enter:
В WSL эти исполняемые файлы обрабатываются аналогично собственным исполняемым файлам Linux. In WSL, these executables are handled similar to native Linux executables. Это означает, что добавление каталогов в путь Linux и их конвейерная передача между командами выполняется должным образом. This means adding directories to the Linux path and piping between commands works as expected. Например: For example: