Bash for linux for windows

Уровень сложностиПростой

Время на прочтение2 мин

Количество просмотров39K

Для пользователя Linux командная строка Windows кажется чем-то непривычным и неудобным. С появлением WSL казалось, что проблема использования Bash решена, но запуск виртуальной машины требует времени, да и пути в WSL отличаются от Windows. Плюс скорость файловых операций на виртуальной машине хуже.

Ещё есть возможность использовать Bash через MSYS2, но мне хотелось найти что-то более компактное и легковесное, а также простое в настройке и установке.

Так как я часто использовал Linux на роутерах, то познакомился с BusyBox, набор UNIX-утилит командной строки, используемой в качестве основного интерфейса во встраиваемых операционных системах. Оказалось, есть версия BusyBox для Windows. В 2020 году появился Windows Terminal, а в нем есть возможность создавать вкладку с запуском конкретной программы.

Пример вкладки Bash

Пример вкладки Bash

Сложив эти два факта, пришла очевидная мысль, использовать BusyBox, содержащий в себе Bash, в Windows Terminal как отдельную консоль.

Список программ входящих в BusyBox

Список программ входящих в BusyBox

Для этого необходимо скачать BusyBox 64, и я, например положил файл в C:/Program Files/Busybox. А дальше создать новый профиль Windows Terminal и поменять его имя на Bash и указать команду для запуска как C:/Program Files/Busybox/busybox64.exe bash

Профиль для Bash

Профиль для Bash

У этого подхода был один минус, при запуске терминала не из конкретной папки, а из ярлыка на рабочем столе или из панели задач.

Запуск терминала из конкретной папки

То адрес рабочей папки был C:/Windows/System32, и если случайно ввести команду удаления или создания файла, то мы портим важную системную папку. Обойти возможно используя аналог .bashrc или /etc/profile или .profile.

Но просто создать файл .profile мало, BusyBox для Windows их не считывает, для этого необходимо добавить путь к этому файлу в  ENV в “Переменные среды”.

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

#!/bin/bash

domain=$(echo $PWD | tr '[:upper:]' '[:lower:]')

if [ $domain = "c:/windows/system32" ]; then
    cd $HOME
fi

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

Мы получили Bash в Windows Terminal с удобной начальной директорией.

Warp Terminal

When Microsoft’s CEO announced that the Bash shell was coming to Windows, several people couldn’t believe it. #BashOnWindows trended on Twitter for days; such was the impact of this news.

Initially referred as Bash on Windows, it is actually called Windows Subsystem for Linux, popularly known as WSL.

With WSL, you can install one of the supported Linux distribution inside Windows and use the Windows terminal to access the Linux systems and run Linux commands.

In this tutorial, you’ll learn how to enable WSL on Windows and then install a Linux distribution of your choice.

📋

This tutorial was tested with the latest Windows 11 version 22H2, and build 22621.819. You might need to update your Windows installation if you have an older build to follow everything in this tutorial.

What is WSL?

WSL (formerly Bash on Windows) provides a Windows subsystem, and Linux runs atop it. It is not a virtual machine or an application like Cygwin. It is a complete Linux system inside Windows 10/11. It allows you to run the same Bash shell you find on Linux. You can run Linux commands inside Windows without installing a virtual machine or dual-boot Linux and Windows.

You install Linux inside Windows like a regular application. This is a good option if your main aim is to learn Linux/UNIX commands.

Check for System Compatibility

You must be running specific versions of Windows for the different features described in this article. Requirements necessary for a particular feature to work are described under its titles. To check your Windows version, search for about in the start menu.

search about in start menu

Search about in the Start Menu

Here, you can see the build of your PC, as shown in the screenshot below. Make sure it is matching with the respective requirements described under various sub-headings here in this article.

checking build number of windows

Checking the build number of Windows
  • You must be running Windows 10 version 1607 (the Anniversary update) or above.
  • WSL only runs on 64-bit versions 32-bit versions are not supported.

Install Bash in Newer Windows 10 and 11

The good thing is that the latest set of upgrades, including the stable release of WSL v1.0 released from Windows, makes it easier to install Bash on Windows.

There are two ways you can go about it:

  1. You can get it in one click from Windows Store.
  2. Choose to use the command-line.

1. Install WSL Using the Microsoft Store

wsl on microsoft store

Launch the Microsoft Store and search for «Windows subsystem«.

Install it, and you’re done with the first step. Next, you have to install a Linux distribution.

So, if you try to open WSL, you will get to see a window informing you that no distribution is installed.

command prompt asking to continue installing distributions

Similar to WSL, search for the distribution on Microsoft Store, and then install it.

For instance, I installed Ubuntu from the store as shown in the image below:

ubuntu 22.04 lts wsl on microsoft store

And, then proceed to «Open» it and it will automatically start installing. The procedure is same for any distribution you choose.

We then have to configure it, which is discussed right after installing it through the command line.

2. Install WSL and the default distribution using the command-line

In WSL, the default distribution is Ubuntu (which can be changed). To install, open Powershell as an administrator.

For this, search for Powershell in the start menu, right-click on Powershell and select Run as Administrator.

run powershell as an administrator

Run Powershell as an administrator

Inside Powershell, enter the following command to install WSL, along with all necessary features and the default distribution, that is, Ubuntu.

wsl --install

Once finished downloading and installing, you need to reboot to apply the changes.

Whether you installed WSL and Ubuntu using the Microsoft Store or the command line, you need to configure it.

Here’s how it is done:

🛠️ Configure the newly installed Ubuntu

After rebooting, search for Ubuntu in Start Menu and open it.

open ubuntu from windows 11 start menu

Open Ubuntu from Windows 11 start menu

It will ask you to enter a UNIX Username and Password. Enter these details and press enter key.

enter unix username and password

Enter UNIX username and password

You will now be inside the terminal window of Ubuntu.

logged into new ubuntu 22.04 lts in windows 11 wsl

Logged into new Ubuntu 22.04 LTS in Windows 11 WSL

Once logged in, you need to update the installed Ubuntu. For this, enter the following commands one by one:

sudo apt update
sudo apt full-upgrade

After completing the update, you are good to go with Ubuntu in WSL.

running ubuntu in wsl 1

Running Ubuntu in WSL

Install Bash on Older Windows

If you have the minimum requirements mentioned in the beginning but are running an older Windows build, the previous method may not be supported. So there is a manual installation method.

Also, there are both WSL1 and WSL2 available. WSL2 offers some upgraded functionalities but has some minimum requirements to run:

  • For x64 systems: Version 1903 or later, with Build 18362 or later.
  • For ARM64 systems: Version 2004 or later, with Build 19041 or later.

So this brings us to two possibilities to install:

  1. Install Ubuntu with WSL1
  2. Install Ubuntu with WSL2

1. Install Ubuntu with WSL 1

This is a relatively simple procedure for those with a system incompatible with WSL2. First, you need to enable the Windows Subsystem for the Linux feature. This can be done through the command line. Open Powershell as an administrator and enter the following command:

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

Or, to do this via GUI, follow the steps below:

windows 10 features enable/disable menu

  1. Search for Windows Features in Start Menu.
  2. Turn on Windows Subsystem for the Linux feature.
  3. Reboot your system.
  4. Open the Windows store and search for the distribution of your choice to install.

Once installation is completed, open the Ubuntu app from the start menu. It will take a couple of seconds to install. You will be prompted to enter a username and password. Provide those credentials, and you are good to go with Ubuntu in WSL1.

2. Install Ubuntu with WSL 2

It is recommended to use WSL2 instead of WSL1 if you have support. To install Ubuntu with WSL2, you need to make sure that the Windows Subsystem for Linux feature is turned on. For this, as in the above case, execute the following command in an elevated Powershell:

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

Reboot the device once the command is completed.

After this, you need to enable the Virtual Machine Platform feature. Open the Powershell with admin privileges and enter the following command:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Once again, restart the device to complete the WSL install and update to WSL 2.

Now, download the Linux Kernel Update Package for x64 machines from the official website. If you are using ARM64 devices, use this link to download the latest kernel update package.

If you are not sure about the device architecture, enter the command below in Powershell to get the type:

systeminfo | find "System Type"

When the file is downloaded, double-click on it and finish the installation of the Kernel update package.

Now, open PowerShell and run this command to set WSL 2 as the default version when installing a new Linux distribution:

wsl --set-default-version 2

Once WSL2 is set as the default version, you can now install the Linux distribution of your choice.

Go to Windows Store and install Ubuntu, as described in the earlier steps. and the rest of the procedure is already described above.

Enjoy Linux inside Windows.

🔧 Troubleshooting Tip 1

«The WSL optional component is not enabled. Please enable it and try again.»

You may see an error like this when you try to run Linux inside Windows 10:

The WSL optional component is not enabled. Please enable it and try again.
See https://aka.ms/wslinstall for details.
Error: 0x8007007e
Press any key to continue...

And when you press any key, the application closes immediately.

The reason here is that the Windows Subsystem for Linux is not enabled in your case. You should enable it as explained in this guide. You can do that even after you have installed Linux.

🔧 Troubleshooting Tip 2

Installation failed with error 0x80070003

This is because Windows Subsystem for Linux only runs on the system drive i.e. the C drive. You should ensure that when you download Linux from the Windows Store, it is stored and installed in the C Drive.

On Windows 10, go to Settings -> Storage -> More Storage Settings -> Where new content is saved: Change where new content is saved and select C Drive here.

windows 10 new app storag location

On Windows 11, go to Settings -> System -> Storage -> Advanced storage settings -> Where new content is saved and select C Drive here.

select the c drive as storage space for new apps in windows 11 settings

Select the C-Drive as storage space for new apps in Windows 11 settings

🔧 Troubleshooting Tip 3

«Failed to attach disk Error»

Sometimes, this error will appear when we reinstall the Ubuntu in WSL.

file not found error in wsl

File not found error in WSL

In this case, open Powershell and run the following command:

wsl -l -v

This will list the installed Linux systems. Find the name of the system, that is throwing the error, in my case Ubuntu. Now run the following command:

wsl --unregister Ubuntu

You can restart the ubuntu app and it will run without any issues.

You can refer to more common troubleshooting methods from the official website.

Run GUI Apps On Windows Subsystem for Linux

The ability to run GUI apps on Windows Subsystem for Linux was introduced with the WSL 2 release in May 2020.

Windows Subsystem for Linux (WSL) with WSL2 now supports running Linux GUI applications (X11 and Wayland) on Windows in a fully integrated desktop experience. This allows you to install Linux applications and seamlessly integrate them into Windows desktop, including features like “pin to taskbar”.

📋

One crucial point is that you must be on Windows 10 Build 19044+ or Windows 11 to access this feature.

Step 1: Enable/Update WSL 2

This procedure has been explained in the above section and you can refer to it.

Step 2: Download and Install Graphics drivers

To run GUI apps, you need to install appropriate graphics drivers. You can use the following link to download the drivers according to your provider.

  • Intel GPU Driver for WSL
  • AMD GPU Driver for WSL
  • NVIDIA GPU Driver for WSL

Once installed, you are all done.

Step 3: Install some GUI Apps

Now, go to your Ubuntu app and install any GUI app using the APT package manager. You should note that running apps from other sources like flatpak are problematic within WSL.

For this article, I installed the Gedit text editor using the following command:

sudo apt install gedit -y

This will install several MB of packages including required libraries. Once completed, you can run the following command to start the GUI Gedit app in Windows.:

gedit
run gedit text editor gui in wsl ubuntu

Run Gedit text editor GUI in WSL Ubuntu

Similarly, you can install all the popular applications available to Linux, including Nautilus file manager, GIMP, etc. For more about running GUI applications in WSL, you can refer to the official documentation.

Install Linux Bash Shell on other older Windows 10

If you cannot get the Fall Creator’s update on Windows 10 for some reason, you can still install it if you have the Anniversary update of Windows 10. But here, you’ll have to enable developer mode. I still recommend upgrading to the Fall Creator’s update or the latest Windows 10 2004 version update though.

Press Windows Key + I to access Windows system settings. Here, go to Update & Security:

select updatesecurity option in windows system settings

Select Updates&Security option in Windows system settings

From the left side pane, choose “For developers.” You’ll see an option for “Developer mode.” Enable it.

select for developers option from the side pane

Select For Developers option from the side pane

Now search for Control Panel and in Control Panel, click on “Programs”:

select programs from the windows control panel

Select Programs from the Windows Control Panel

In Programs, click “Turn Windows features on or off”:

select turn windows feature on or off from programs and features section

Select Turn Windows features on or off from the Programs and Features section

When you do this, you’ll see several Windows features. Look for “Windows Subsystem for Linux” and enable it.

select the windows subsystem for linux checkbox

Select the Windows Subsystem for Linux checkbox

You’ll need to restart the system after doing this.

restart the device to apply the changes

Restart the device to apply the changes

After restarting the computer, click the start button and search for “bash”.

select bash from windows start menu

Select Bash from Windows Start Menu

When you run it for the first time, you’ll be given the option to download and install Ubuntu. You’ll be asked to create a username and password during this process. It will install an entire Ubuntu Linux system, so have patience as it will take some time in downloading and installing Linux on Windows.

running ubuntu inside windows

Running Ubuntu inside Windows

Once this is done, go back to the Start menu and search for Ubuntu or Bash.

search for ubuntu or bash in windows start menu

Search for Ubuntu or Bash in Windows Start Menu

Now you have a command line version of Ubuntu Linux. You can use apt to install various command line tools in it.

checking the working of bash shell in windows

Checking the working of Bash shell in Windows

💬 I hope you find this tutorial helpful for installing bash on Windows and experimenting with Linux GUI apps on Windows. No wonder WSL lets you play with Linux inside of Windows. If you have questions or suggestions, feel free to ask.

Here’s how to set up and use the Linux shell on Windows – using the Windows Subsystem for Linux (WSL).

This tutorial is intended for up-to-date versions of Windows 10 from 2020 onwards. I’m not going to cover how to use WSL on older versions of Windows 10 or other methods for Windows 8/7/XP/3.1 because you shouldn’t be using outdated software. If you must use Windows, use a version that still receives security patches!

WSL is a great tool and allows you to pretty much run Linux software on windows as if you had never left Linux. Not everyone has the luxury of being able to install a Linux system due to relying on proprietary software released only for Windows.

Anyway, here’s how to get a Linux shell happening on Windows 10, courtesy of the Windows Subsystem for Linux.

Install Windows Subsystem for Linux

First, you will need to install support for the Windows Subsystem for Linux in Windows 10.

bash windows 7

This is done from the Settings app – so open it up and then click on Apps.

bash windows 8

Then click on Programs and Features in the sidebar to the right.

bash windows 9

Next, click Turn Windows features on or off in the sidebar to the left.

bash windows 11

Scroll down the list and check Windows Subsystem for Linux, then press OK

Confirm your selection, then allow your computer to restart to complete the installation.

Install Ubuntu From The Windows Store

First, make sure that your copy of Windows 10 is completely up-to-date. Older releases of Windows 10 from before 2020 do not support the Windows Subsystem for Linux.

bash windows 2

Next, open the Microsoft Store from the Start Menu, or search for ‘store.’

bash windows 3

Search for ‘Ubuntu’ from Canonical.

To install it, click ‘Get’ and wait for it to download.

This “App” contains a full copy of Ubuntu for the Windows Subsystem for Linux – including the Bash shell, and a full Ubuntu command line environment.

bash windows 4

Launch the downloaded Ubuntu App by clicking ‘Launch.’

bash windows 5

A shortcut to Ubuntu will also be added to your start menu.

bash windows 12 1

When you launch Ubuntu, you’ll be dropped right into a Linux Bash environment in Windows – cool!

Install the Windows Terminal (Optional)

The terminal which Ubuntu opens is a bit lacking, however. There’s a better Terminal App now available – The Windows Terminal!

Windows Terminal supports things like tabs and custom configurations. You can have a Powershell tab open next to a Bash Terminal; it’s really nice.

It’s in the Windows Store, so search for it and install it.

bash windows 14 1

bash windows 15 1

Conclusion

Windows is still the industry standard for many fields – including graphic design and CAD. Some software development tools are also only supported on Windows.

If you rely on software that can only be run on Windows, running and testing Linux software without having to rely on a cumbersome virtual machine saves both time and resources.

Под 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.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Шаг 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 от имени администратора следующую команду:

wsl —set-default-version 2

Шаг 5. После перезагрузки откройте фирменный магазин приложений Microsoft Store и найдите подходящий GNU/Linux-дистрибутив. Самым популярным является Ubuntu — вы можете установить любую версию из представленных в Microsoft Store.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Шаг 6. Как только установка завершится, найдите дистрибутив в меню «Пуск» и запустите его.

Шаг 7. Пройдите этап первоначальной настройки, введя имя нового пользователя и придумав пароль.

Шаг 8. Теперь различные GNU/Linux-команды можно выполнять, запустив дистрибутив, либо введя в командной строке wsl <команда>. Например, для просмотра всех файлов в текущей директории достаточно в командной строке выполнить wsl ls -a.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Обращу внимание на то, что путь к дискам в WSL отличается от такового в Windows. Вместо привычного C:/ используйте /mnt/c/. Также не забывайте про экранирование пробелов с помощью символа \ — это также пригодится при вводе путей к файлам.

Помимо выполнения базовых команд, с помощью WSL можно даже запускать приложения с графическим интерфейсом. Правда, рассчитывать на большое количество поддерживаемых подобных программ не стоит.

Шаг 1. Загрузите X-сервер и установите его.

Шаг 2. Запустите его с помощью ярлыка на рабочем столе. В открывшемся окне выберите вариант Multiple windows, затем Start no client. Завершите настройку кнопкой Finish.

Шаг 3. Откройте дистрибутив через меню Пуск и выполните команду export DISPLAY=:0

Шаг 4. Запустив приложение с графическим интерфейсом в WSL, вы увидите новое окно прямо в Windows.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

CoreUtils — лёгкий инструмент для запуска базовых команд

Плюс данной утилиты — возможность запуска не только на Windows 10, но и на более старых версиях ОС. Кроме того, она легка и не занимает много места. Не обошлось без недостатков — программа скудна на функционал и не обновлялась очень давно. Она не только не умеет запускать скрипты и приложения с GUI, но и поддерживает лишь самые базовые GNU/Linux-команды. Установка CoreUtils весьма проста.

Шаг 1. Скачайте утилиту с официального сайта.

Шаг 2. Следуйте инструкциям установщика.

Шаг 3. Откройте «Панель управления», в разделе «Система и безопасность» выберите пункт «Система». На панели слева откройте «Дополнительные параметры системы». Нажмите кнопку «Переменные среды» и в открывшемся окне найдите область с заголовком «Системные переменные». В случае, когда там есть переменная Path, выберите её, нажмите «Изменить» и далее создайте новую строку. Содержимым этой строки должен быть путь к папке, который был указан при установке. Если вы ничего не меняли, то введите следующее:

C:\Program Files (x86)\GnuWin32\bin

Переменной Path нет? Тогда для начала создайте её кнопкой «Создать», затем в поле имени введите Path, а в поле значения — строку выше.

Шаг 4. Запустите командную строку и выполняйте команды прямо там.

Cygwin — запуск команд и Bash-скриптов

Ещё одна утилита, схожая с CoreUtils, но обладающая более широким функционалом — в том числе и возможностью запуска скриптов. Из минусов — немалый вес и более сложная установка. Разумеется, не идёт ни в какое сравнение с максимально удобным WSL, но для базовых команд вполне подойдёт.

Шаг 1. Загрузите Cygwin и запустите установку.

Шаг 2. Выберите Install from Internet, укажите директории для установки и загрузки пакетов, а также любой подходящий сайт из списка для скачивания файлов.

Шаг 3. В процессе установки можете выбрать необходимые пакеты, либо сразу нажать «Далее», оставив базовый набор.

Шаг 4. Откройте «Панель управления», в разделе «Система и безопасность» выберите пункт «Система». На панели слева откройте «Дополнительные параметры системы». Нажмите кнопку «Переменные среды» и в открывшемся окне найдите область с заголовком «Системные переменные». В случае, когда там есть переменная Path, выберите её, нажмите «Изменить» и далее создайте новую строку. Содержимым этой строки должен быть путь к папке, который был указан при установке. Если вы ничего не меняли, то введите следующее:

C:\cygwin64\bin

Переменной Path нет? Тогда для начала создайте её кнопкой «Создать», затем в поле имени введите Path, а в поле значения — строку выше.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Шаг 5. Команды можно выполнять как через командную строку, так и через специальный терминал.

Шаг 6. Для удаления Cygwin достаточно удалить папку, в которую программа была установлена, а также (по желанию) значение из переменной Path по методу, обратному тому, что был описан в 4 шаге (не удаляйте саму переменную).

В Windows 10 появилась новая возможность для разработчиков — оболочка Ubuntu Bash, позволяющая запускать, устанавливать приложения Linux, использовать скрипты bash прямо в Windows 10, все это называется «Подсистема Windows для Linux». В версии Windows 10 1709 Fall Creators Update доступны уже три дистрибутива Linux для установки. Во всех случаях требуется 64-разрядная система для установки.

В этой инструкции — о том, как установить Ubuntu, OpenSUSE или SUSE Linux Enterprise Server в Windows 10 и некоторые примеры использования в конце статьи. Следует также учитывать, что есть некоторые ограничения при использовании bash в Windows: например, нельзя запускать GUI приложения (правда, сообщают об обходных путях с помощью X server). Кроме этого, командами bash нельзя запустить Windows-программы, несмотря на наличие полного доступа к файловой системе ОС.

Установка Ubuntu, OpenSUSE или SUSE Linux Enterprise Server в Windows 10

Начиная с версии Windows 10 Fall Creators Update (версия 1709) установка подсистемы Linux для Windows несколько изменилась по сравнению с тем, что было в предыдущих версиях (для предыдущих версий, начиная с 1607, когда функция была представлена в бета-версии, инструкция — во второй части этой статьи). Также обратите внимание, что в Windows 10 2004 можно установить Kali Linux с графическим интерфейсом.

Теперь необходимые шаги выглядят следующим образом:

  1. Прежде всего, необходимо включить компонент «Подсистема Windows для Linux» в «Панель управления» — «Программы и компоненты» — «Включение и отключение компонентов Windows». 
    Включение компонентов Linux для Windows 10

  2. После установки компонентов и перезагрузки компьютера, зайдите в Магазин приложений Windows 10 и загрузите оттуда Ubuntu, OpenSUSE или SUSE Linux ES (да, теперь доступно три дистрибутива). При загрузке возможны некоторые нюансы, о которых далее в примечаниях. 
    Дистрибутивы Linux в магазине Windows 10

  3. Запустите загруженный дистрибутив как обычное приложение Windows 10 и выполните первоначальную настройку (имя пользователя и пароль). 
    Настройка Ubuntu Linux в Windows 10 1709

Для включения компонента «Подсистема Windows для Linux» (первый шаг) можно использовать команду PowerShell:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

Теперь несколько примечаний, которые могут быть полезны при установке:

  • Вы можете установить сразу несколько дистрибутивов Linux.
  • При загрузке дистрибутивов Ubuntu, OpenSUSE и SUSE Linux Enterprise Server в русскоязычном магазине Windows 10 заметил следующий нюанс: если просто ввести название и нажать Enter, то нужных результатов в поиске не оказывается, но если начать вводить и затем нажать по появляющейся подсказке, автоматически попадаешь на нужную страницу. На всякий случай прямые ссылки на дистрибутивы в магазине: Ubuntu, OpenSUSE, SUSE LES.
  • Запускать Linux можно и из командной строки (не только с плитки в меню Пуск): ubuntu, opensuse-42 или sles-12

Установка Bash в Windows 10 1607 и 1703

Для того, чтобы установить оболочку bash, выполните следующие простые действия.

  1. Зайдите в параметры Windows 10 — Обновление и безопасность — Для разработчиков. Включите режим разработчика (должен быть подключен Интернет для загрузки необходимых компонентов). 
    Включение режима разработчика в Windows 10

  2. Зайдите в панель управления — Программы и компоненты — Включение или отключение компонентов Windows, отметьте пункт «Подсистема Windows для Linux». 
    Установка подсистемы Linux в Windows 10

  3. После установки компонентов, введите в поиске Windows 10 «bash», запустите предлагаемый вариант приложения и выполните установку. Вы можете задать свое имя пользователя и пароль для bash, либо использовать пользователя root без пароля. 
    Установка Ubuntu bash

По завершении установки вы можете запускать Ubuntu Bash на Windows 10 через поиск, или создав ярлык для оболочки там, где вам требуется.

Примеры использования Ubuntu Shell в Windows

Для начала отмечу, что автор не является специалистом по bash, Linux и разработке, а примеры ниже — просто демонстрация того, что в Windows 10 bash работает с ожидаемыми результатами для тех, кто разбирается в этом.

Приложения Linux

Приложения в Windows 10 Bash можно устанавливать, удалять и обновлять с помощью apt-get (sudo apt-get) из репозитория Ubuntu.

apt-get install в Windows 10

Использование приложений с текстовым интерфейсом ничем не отличается от такового на Ubuntu, например, вы можете установить Git в Bash и использовать его привычным образом.

Использование bash git в Windows 10

Скрипты bash

Вы можете запускать скрипты bash в Windows 10, создать их можно в имеющемся в оболочке текстовом редакторе Nano.

Скрипты bash в Windows 10

Скрипты bash не могут вызвать программы и команды Windows, но возможен запуск скриптов и команд bash из bat файлов и сценариев PowerShell:

bash -c "команда"

Также вы можете попробовать запускать приложения с графическим интерфейсом в Ubuntu Shell в Windows 10, на этот счет в Интернете уже имеется не одна инструкция и суть способа сводится к использованию Xming X Server для вывода GUI приложения. Хотя официально возможность работы с такими приложениями Майкрософт не заявлена.

Как было написано выше, я не тот человек, который может в полной степени оценить ценность и функциональность нововведения, но вижу как минимум одно применение для себя: различные курсы Udacity, edX и другие, связанные с разработкой проходить будет куда проще, работая с необходимыми инструментами прямо в bash (а в этих курсах обычно демонстрируется работа именно в терминале MacOS и Linux bash).

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Что такое hp smart в windows 10
  • Как отключить всплывающее окно безопасность windows
  • Как удалить officesuite с компьютера windows 10
  • Программа для объединения жесткого диска windows 10 на русском языке
  • Realworld cursor editor для windows 10