- 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
- 4 Ways to Run Linux Commands in Windows
- Using Linux commands inside Windows
- 1. Use Linux Bash Shell on Windows 10
- 2. Use Git Bash to run Bash commands on Windows
- 3. Using Linux commands in Windows with Cygwin
- 4. Use Linux in virtual machine
- Как выполнять Linux-команды внутри Windows: официальный и сторонние способы
- Содержание
- WSL — официальная подсистема Linux внутри Windows
- CoreUtils — лёгкий инструмент для запуска базовых команд
- Cygwin — запуск команд и Bash-скриптов
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.
Источник
4 Ways to Run Linux Commands in Windows
Last updated October 29, 2020 By Abhishek Prakash 18 Comments
Brief: Want to use Linux commands but don’t want to leave Windows? Here are several ways to run Linux bash commands in Windows.
If you are learning Shell scripting probably as a part of your course curriculum, you need to use Linux commands to practice the commands and scripting.
Your school lab might have Linux installed but personally you don’t have a Linux laptop but the regular Windows computer like everyone else. Your homework needs to run Linux commands and you wonder how to run Bash commands and scripts on Windows.
You can install Linux alongside Windows in dual boot mode. This method allows you to choose either Linux or Windows when you start your computer. But taking all the trouble to mess with partitions for the sole purpose of running Linux command may not be for everyone.
You can also use Linux terminals online but your work won’t be saved here.
The good news is that there are several ways you can run Linux commands inside Windows, like any regular application. Isn’t it cool?
Using Linux commands inside Windows
As an ardent Linux user and promoter, I would like to see more and more people using ‘real’ Linux but I understand that at times, that’s not the priority. If you are just looking to practice Linux to pass your exams, you can use one of these methods for running Bash commands on Windows.
1. Use Linux Bash Shell on Windows 10
Did you know that you can run a Linux distribution inside Windows 10? The Windows Subsystem for Linux (WSL) allows you to run Linux inside Windows. The upcoming version of WSL will be using the real Linux kernel inside Windows.
This WSL, also called Bash on Windows, gives you a Linux distribution in command line mode running as a regular Windows application. Don’t be scared with the command line mode because your purpose is to run Linux commands. That’s all you need.
You can find some popular Linux distributions like Ubuntu, Kali Linux, openSUSE etc in Windows Store. You just have to download and install it like any other Windows application. Once installed, you can run all the Linux commands you want.
Linux distributions in Windows 10 Store
2. Use Git Bash to run Bash commands on Windows
You probably know what Git is. It’s a version control system developed by Linux creator Linus Torvalds.
Git for Windows is a set of tools that allows you to use Git in both command line and graphical interfaces. One of the tools included in Git for Windows is Git Bash.
Git Bash application provides and emulation layer for Git command line. Apart from Git commands, Git Bash also supports many Bash utilities such as ssh, scp, cat, find etc.
In other words, you can run many common Linux/Bash commands using the Git Bash application.
You can install Git Bash in Windows by downloading and installing the Git for Windows tool for free from its website.
3. Using Linux commands in Windows with Cygwin
If you want to run Linux commands in Windows, Cygwin is a recommended tool. Cygwin was created in 1995 to provide a POSIX-compatible environment that runs natively on Windows. Cygwin is a free and open source software maintained by Red Hat employees and many other volunteers.
For two decades, Windows users use Cygwin for running and practicing Linux/Bash commands. Even I used Cygwin to learn Linux commands more than a decade ago.
You can download Cygwin from its official website below. I also advise you to refer to this Cygwin cheat sheet to get started with it.
4. Use Linux in virtual machine
Another way is to use a virtualization software and install Linux in it. This way, you install a Linux distribution (with graphical interface) inside Windows and run it like a regular Windows application.
This method requires that your system has a good amount of RAM, at least 4 GB but better if you have over 8 GB of RAM. The good thing here is that you get the real feel of using a desktop Linux. If you like the interface, you may later decide to switch to Linux completely.
There are two popular tools for creating virtual machines on Windows, Oracle VirtualBox and VMware Workstation Player. You can use either of the two. Personally, I prefer VirtualBox.
Conclusion
The best way to run Linux commands is to use Linux. When installing Linux is not an option, these tools allow you to run Linux commands on Windows. Give them a try and see which method is best suited for you.
Like what you read? Please share it with others.
Источник
Как выполнять Linux-команды внутри Windows: официальный и сторонние способы
Под GNU/Linux-дистрибутивы создано огромное количество полезных и удобных инструментов и приложений для обычных пользователей и разработчиков. Далеко не всё из этого доступно на Windows, но, к счастью, для ОС от Microsoft есть решения, исправляющие эту проблему.
Содержание
WSL — официальная подсистема Linux внутри Windows
В Windows 10 существует крайне полезная вещь под названием Windows Subsystem for Linux (WSL). Она позволяет использовать GNU/Linux-среду прямо в Windows и запускать не только команды, но и, например, Bash-скрипты. Для использования WSL необходимо следовать инструкции ниже.
Шаг 1. Проверьте, подходит ли текущая версия Windows требованиям. Для этого нажмите сочетание клавиш Win+R, затем введите winver. Найдите строку «Сборка ОС» — она должна быть свежее версии 14316.
Шаг 2. Запустите стандартную утилиту PowerShell от имени администратора и введите в ней команду для включения WSL:
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
Шаг 3. Если версия Windows, определённая в первом пункте, свежее 18362, вы можете установить WSL 2, который в разы быстрее первой версии и обладает доработанным ядром. Введите команду ниже, если нужно установить WSL 2:
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
После этого скачайте и установите пакет обновления с официального сайта.
Шаг 4. Перезагрузите компьютер. Если была произведена установка WSL 2, введите в PowerShell от имени администратора следующую команду:
Шаг 5. После перезагрузки откройте фирменный магазин приложений Microsoft Store и найдите подходящий GNU/Linux-дистрибутив. Самым популярным является Ubuntu — вы можете установить любую версию из представленных в Microsoft Store.
Шаг 6. Как только установка завершится, найдите дистрибутив в меню «Пуск» и запустите его.
Шаг 7. Пройдите этап первоначальной настройки, введя имя нового пользователя и придумав пароль.
Шаг 8. Теперь различные GNU/Linux-команды можно выполнять, запустив дистрибутив, либо введя в командной строке wsl . Например, для просмотра всех файлов в текущей директории достаточно в командной строке выполнить wsl ls -a.
Обращу внимание на то, что путь к дискам в WSL отличается от такового в Windows. Вместо привычного C:/ используйте /mnt/c/. Также не забывайте про экранирование пробелов с помощью символа \ — это также пригодится при вводе путей к файлам.
Помимо выполнения базовых команд, с помощью WSL можно даже запускать приложения с графическим интерфейсом. Правда, рассчитывать на большое количество поддерживаемых подобных программ не стоит.
Шаг 1. Загрузите X-сервер и установите его.
Шаг 2. Запустите его с помощью ярлыка на рабочем столе. В открывшемся окне выберите вариант Multiple windows, затем Start no client. Завершите настройку кнопкой Finish.
Шаг 3. Откройте дистрибутив через меню Пуск и выполните команду export DISPLAY=:0
Шаг 4. Запустив приложение с графическим интерфейсом в WSL, вы увидите новое окно прямо в Windows.
CoreUtils — лёгкий инструмент для запуска базовых команд
Плюс данной утилиты — возможность запуска не только на Windows 10, но и на более старых версиях ОС. Кроме того, она легка и не занимает много места. Не обошлось без недостатков — программа скудна на функционал и не обновлялась очень давно. Она не только не умеет запускать скрипты и приложения с GUI, но и поддерживает лишь самые базовые GNU/Linux-команды. Установка CoreUtils весьма проста.
Шаг 1. Скачайте утилиту с официального сайта.
Шаг 2. Следуйте инструкциям установщика.
Шаг 3. Откройте «Панель управления», в разделе «Система и безопасность» выберите пункт «Система». На панели слева откройте «Дополнительные параметры системы». Нажмите кнопку «Переменные среды» и в открывшемся окне найдите область с заголовком «Системные переменные». В случае, когда там есть переменная Path, выберите её, нажмите «Изменить» и далее создайте новую строку. Содержимым этой строки должен быть путь к папке, который был указан при установке. Если вы ничего не меняли, то введите следующее:
Переменной Path нет? Тогда для начала создайте её кнопкой «Создать», затем в поле имени введите Path, а в поле значения — строку выше.
Шаг 4. Запустите командную строку и выполняйте команды прямо там.
Cygwin — запуск команд и Bash-скриптов
Ещё одна утилита, схожая с CoreUtils, но обладающая более широким функционалом — в том числе и возможностью запуска скриптов. Из минусов — немалый вес и более сложная установка. Разумеется, не идёт ни в какое сравнение с максимально удобным WSL, но для базовых команд вполне подойдёт.
Шаг 1. Загрузите Cygwin и запустите установку.
Шаг 2. Выберите Install from Internet, укажите директории для установки и загрузки пакетов, а также любой подходящий сайт из списка для скачивания файлов.
Шаг 3. В процессе установки можете выбрать необходимые пакеты, либо сразу нажать «Далее», оставив базовый набор.
Шаг 4. Откройте «Панель управления», в разделе «Система и безопасность» выберите пункт «Система». На панели слева откройте «Дополнительные параметры системы». Нажмите кнопку «Переменные среды» и в открывшемся окне найдите область с заголовком «Системные переменные». В случае, когда там есть переменная Path, выберите её, нажмите «Изменить» и далее создайте новую строку. Содержимым этой строки должен быть путь к папке, который был указан при установке. Если вы ничего не меняли, то введите следующее:
Переменной Path нет? Тогда для начала создайте её кнопкой «Создать», затем в поле имени введите Path, а в поле значения — строку выше.
Шаг 5. Команды можно выполнять как через командную строку, так и через специальный терминал.
Шаг 6. Для удаления Cygwin достаточно удалить папку, в которую программа была установлена, а также (по желанию) значение из переменной Path по методу, обратному тому, что был описан в 4 шаге (не удаляйте саму переменную).
Источник