Windows command line from linux

Справочные материалы по командам подсистемы Windows для Linux Command Reference for Windows Subsystem for Linux

Лучший способ взаимодействовать с подсистемой Windows для Linux — использовать команду wsl.exe . The best way to interact with the Windows Subsystem for Linux is to use the wsl.exe command.

Задать WSL 2 в качестве версии по умолчанию Set WSL 2 as your default version

Выполните следующую команду в PowerShell, чтобы задать WSL 2 в качестве версии по умолчанию при установке нового дистрибутива Linux: Run the following command in Powershell to set WSL 2 as the default version when installing a new Linux distribution:

Установите вашу версию дистрибутива на WSL 1 или WSL 2 Set your distribution version to WSL 1 or WSL 2

Вы можете проверить версию WSL, назначенную каждому из установленных дистрибутивов Linux, открыв командную строку PowerShell и введя команду (доступна только в сборке Windows 19041 или более поздней версии): wsl -l -v . You can check the WSL version assigned to each of the Linux distributions you have installed by opening the PowerShell command line and entering the command (only available in Windows Build 19041 or higher): wsl -l -v

Чтобы настроить дистрибутив для одной из версий WSL, выполните: To set a distribution to be backed by either version of WSL please run:

Не забудьте заменить на фактическое имя дистрибутива и с номером «1» или «2». Make sure to replace with the actual name of your distribution and with the number ‘1’ or ‘2’. Вы можете всегда вернуться к WSL версии 1, выполнив эту команду и заменив «2» на «1». You can change back to WSL 1 at anytime by running the same command as above but replacing the ‘2’ with a ‘1’.

Кроме того, если вы хотите сделать WSL 2 архитектурой по умолчанию, выполните следующую команду: Additionally, if you want to make WSL 2 your default architecture you can do so with this command:

Будет установлена версия любого нового дистрибутива, установленного в WSL 2. This will set the version of any new distribution installed to WSL 2.

wsl.exe

Ниже приведен список, содержащий все параметры wsl.exe при использовании в Windows версии 1903. Below is a list containing all options when using wsl.exe as of Windows Version 1903.

Использование: wsl [Argument] [Options. ] [CommandLine] Using: wsl [Argument] [Options. ] [CommandLine]

Аргументы для выполнения команд Linux Arguments for running Linux commands

Без аргументов Without arguments

Если командная строка не указана, wsl.exe запускает оболочку по умолчанию. If no command line is provided, wsl.exe launches the default shell.

—exec, -e —exec, -e

Выполнение указанной команды без использования оболочки Linux по умолчанию. Execute the specified command without using the default Linux shell.

Остальная часть командной строки передается «как есть». Pass the remaining command line as is.

Приведенные выше команды также принимают следующие параметры. The above commands also accept the following options:

—distribution, -d —distribution, -d

Запуск указанного дистрибутива. Run the specified distribution.

—user, -u —user, -u

Выполнение от имени указанного пользователя. Run as the specified user.

Аргументы для управления подсистемой Windows для Linux Arguments for managing Windows Subsystem for Linux

—export —export

Экспорт дистрибутива в TAR-файл. Exports the distribution to a tar file. Именем файла может быть «-» для стандартного вывода. The filename can be — for standard output.

—import —import

Импорт указанного TAR-файла в качестве нового дистрибутива. Imports the specified tar file as a new distribution. Именем файла может быть «-» для стандартного ввода. The filename can be — for standard input.

—list, -l [параметры] —list, -l [Options]

Вывод списка дистрибутивов. Lists distributions.

—all —all

Вывод списка всех дистрибутивов, включая дистрибутивы, которые сейчас устанавливаются или удаляются. List all distributions, including distributions that are currently being installed or uninstalled.

—running —running

Читайте также:  Операционные системы linux 2021

Вывод списка всех дистрибутивов, выполняемых в данный момент. List only distributions that are currently running.

—set-default, -s —set-default, -s

Указание дистрибутива, используемого по умолчанию. Sets the distribution as the default.

—terminate, -t —terminate, -t

Завершение указанного дистрибутива. Terminates the specified distribution.

—unregister —unregister

Отмените регистрацию дистрибутива. Un-register the distribution.

—help отображает сведения об использовании. —help Display usage information.

Дополнительные команды Additional Commands

Доступны также устоявшиеся команды для взаимодействия с подсистемой Windows для Linux. There are also historic commands to interact with the Windows Subsystem for Linux. Их функциональные возможности реализованы в wsl.exe , но эти команды по-прежнему можно использовать. Their functionality is encompassed within wsl.exe , but they are still available for use.

wslconfig.exe

Эта команда позволяет настроить дистрибутив WSL. This command lets you configure your WSL distribution. Ниже приводится список ее параметров. Below is a list of its options.

Использование: wslconfig [Argument] [Options. ] Using: wslconfig [Argument] [Options. ]

Аргументы Arguments

/l, /list [параметры] /l, /list [Options]

Вывод списка зарегистрированных дистрибутивов. Lists registered distributions.

/all Дополнительный вывод списка всех дистрибутивов, включая дистрибутивы, которые сейчас устанавливаются или удаляются. /all Optionally list all distributions, including distributions that are currently being installed or uninstalled.

/running Вывод списка всех дистрибутивов, выполняемых в данный момент. /running List only distributions that are currently running.

/s, /setdefault Задание дистрибутива, используемого по умолчанию. /s, /setdefault Sets the distribution as the default.

/t, /terminate Завершение работы дистрибутива. /t, /terminate Terminates the distribution.

/u, /unregister Отмена регистрации дистрибутива. /u, /unregister Un-registers the distribution.

/upgrade Обновление дистрибутива до файловой системы WslFs. /upgrade Upgrades the distribution to the WslFs file system format.

bash.exe

Эта команда используется для запуска оболочки Bash. This command is used to start a bash shell. Ниже приведены параметры, которые можно использовать с этой командой. Below are the options you can use with this command.

Использование: bash [Options. ] Using: bash [Options. ]

Параметр не задан No Option given

Запуск оболочки Bash в текущем каталоге. Launches the Bash shell in the current directory. Если оболочка Bash не установлена, автоматически запускается lxrun /install . If the Bash shell is not installed automatically runs lxrun /install

запускает оболочку Bash в корневом каталоге пользователя. bash

launches the bash shell into the user’s home directory. Это аналог команды cd

. Similar to running cd

-c -c » «

Выполнение команды, вывод выходных данных и возврат в командную строку Windows. Runs the command, prints the output and exits back to the Windows command prompt.

Пример: bash -c «ls» . Example: bash -c «ls» .

‼️ 4 способа запустить команды Linux в Windows

Краткое описание: Хотите использовать команды Linux, но не хотите выходить из Windows? Вот несколько способов запуска команд Linux bash в Windows.

Если вы изучаете скрипты оболочки, вероятно, как часть вашей учебной программы, вам нужно использовать команды Linux для практики команд и скриптов.

В вашей школьной лаборатории может быть установлен Linux, но лично у вас нет ноутбука с Linux, а обычный компьютер с Windows, как и у всех.

Ваша домашняя работа должна выполняться с командами Linux, и вы задаетесь вопросом, как запускать команды и скрипты Bash в Windows.

Вы можете установить Linux вместе с Windows в режиме двойной загрузки.

Этот метод позволяет вам выбрать Linux или Windows при запуске компьютера.

Но взять на себя все усилия, чтобы связываться с разделами с единственной целью запуска команды Linux, может быть не для всех актуальна.

Вы также можете использовать терминалы Linux онлайн, но ваша работа не будет сохранена.

Хорошая новость заключается в том, что есть несколько способов запуска команд Linux внутри Windows, как и в любом обычном приложении. Разве это не круто?

Использование команд Linux внутри Windows

Как “промоутер” Linux, я бы хотел, чтобы все больше и больше людей использовали «настоящий» Linux, но я понимаю, что иногда это не является приоритетом.

Если вы просто хотите попрактиковаться в Linux, вы можете использовать один из этих методов для запуска команд Bash в Windows.

1. Используйте оболочку Linux Bash в Windows 10

Знаете ли вы, что вы можете запустить дистрибутив Linux внутри Windows 10?

Подсистема Windows для Linux (WSL) позволяет запускать Linux внутри Windows.

В следующей версии WSL будет использоваться настоящее ядро Linux внутри Windows.

Этот WSL, также называемый Bash для Windows, дает вам дистрибутив Linux в режиме командной строки, работающий как обычное приложение Windows.

Не пугайтесь режима командной строки, потому что ваша цель – запускать команды Linux. Это все, что вам нужно.

Вы можете найти некоторые популярные дистрибутивы Linux, такие как Ubuntu, Kali Linux, openSUSE и т. д. В Магазине Windows.

Вам просто нужно скачать и установить его, как любое другое приложение Windows.

После установки вы можете запускать все необходимые вам команды Linux.

Читайте также:  Linux server для windows клиентов

2. Используйте Git Bash для запуска команд Bash в Windows

Вы, наверное, знаете, что такое Git.

Это система контроля версий, разработанная создателем Linux Линусом Торвальдсом

Git для Windows – это набор инструментов, который позволяет использовать Git как в командной строке, так и в графических интерфейсах.

Одним из инструментов, включенных в Git для Windows, является Git Bash.

Приложение Git Bash предоставляет и слой эмуляции для командной строки Git.

Помимо команд Git, Git Bash также поддерживает множество утилит Bash, таких как ssh, scp, cat, find и т. д.

Другими словами, вы можете запускать множество общих команд Linux / Bash, используя приложение Git Bash.

Вы можете установить Git Bash в Windows, скачав и бесплатно установив инструмент Git для Windows с веб-сайта:

3. Использование команд Linux в Windows с Cygwin

Если вы хотите запускать команды Linux в Windows, рекомендуется Cygwin.

Cygwin был создан в 1995 году для обеспечения POSIX-совместимой среды, которая изначально работает в Windows.

Cygwin – это бесплатное программное обеспечение с открытым исходным кодом, поддерживаемое сотрудниками Red Hat и многими другими добровольцами.

В течение двух десятилетий пользователи Windows используют Cygwin для запуска и выполнения команд Linux / Bash.

Вы можете скачать Cygwin с официального сайта, который будет показан ниже.

4. Используйте Linux на виртуальной машине

Другой способ – использовать программное обеспечение для виртуализации и установить в него Linux.

Таким образом, вы устанавливаете дистрибутив Linux (с графическим интерфейсом) внутри Windows и запускаете его как обычное приложение Windows.

Этот метод требует, чтобы в вашей системе было достаточно оперативной памяти, по крайней мере, 4 ГБ, но лучше, если у вас более 8 ГБ.

Здесь хорошо то, что вы по-настоящему почувствуете использование настольного Linux. Если вам нравится интерфейс, вы можете позже полностью перейти на Linux.

Существует два популярных инструмента для создания виртуальных машин в Windows: Oracle VirtualBox и VMware Workstation Player.

Вы можете использовать любой из двух. Лично я предпочитаю VMware.

Windows interoperability with Linux

The Windows Subsystem for Linux (WSL) is continuously improving integration between Windows and Linux. You can:

  • 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+)

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.

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 .

\’` 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:

  • 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 2012

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

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.

Earlier versions of Windows 10

There are several differences for the interoperability commands on earlier Windows 10 versions. 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 has been replaced with wsl.exe .
  • -c option for running a single command isn’t needed with wsl.exe .
  • Windows path is included in the WSL $PATH .
  • The process for disabling interop is unchanged.

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.

The WSL commands passed into bash -c are forwarded to the WSL process without modification. File paths must be specified in the WSL format and care must be taken to escape relevant characters. Example:

When calling a Windows tool from a WSL distribution in an earlier version of Windows 10, you will need to specify the directory path. For example, from your WSL command line, enter:

In WSL, these executables are handled similar to native Linux executables. This means adding directories to the Linux path and piping between commands works as expected. For example:

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