Bash for linux for windows

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

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

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

Для пользователя 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 с удобной начальной директорией.

Linux on Windows is a reality, thanks to the partnership between Canonical (parent company of Ubuntu) and Microsoft.

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.

But Bash on Windows (or Windows Subsystem for Linux) was not available to everyone immediately. People had to install the Windows 10 technical preview to install Linux on Windows 10.

That’s not the case anymore; it is pretty easy to install and use WSL now!

📋

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 Bash on Windows?

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.

Quick Links

  • What You Need to Know About Windows 10’s Bash Shell
  • How to Install Bash on Windows 10
  • How to Use The Bash Shell and Install Linux Software
  • Bonus: Install the Ubuntu Font for a True Ubuntu Experience

Key Takeaways

First, enable the Windows Subsystem for Linux (WSL) from the Features window or via the «wsl —install» command. After rebooting your PC, install Ubuntu or any other Linux distribution of your choice from the Microsoft Store.

The Windows Subsystem for Linux, introduced in the Anniversary Update, became a stable feature in the Fall Creators Update. You can now run Ubuntu, openSUSE, a remix of Fedora, and plenty of others on Windows, with more Linux distributions coming soon.

What You Need to Know About Windows 10’s Bash Shell

How Windows Subsystem for Linux 1 (WSL1) Works

Windows 10 offers a full Windows Subsystem intended for Linux (WSL) for running Linux software. This isn’t a virtual machine, a container, or Linux software compiled for Windows (like Cygwin). It’s based on Microsoft’s abandoned Project Astoria work for running Android apps on Windows.

Think of it as the opposite of Wine. While Wine allows you to run Windows applications directly on Linux, the Windows Subsystem for Linux allows you to run Linux applications directly on Windows.

Microsoft worked with Canonical to offer a full Ubuntu-based Bash shell environment that runs atop this subsystem. Technically, this isn’t Linux at all. Linux is the underlying operating system kernel, and that isn’t available here. Instead, this allows you to run the Bash shell and the exact same binaries you’d normally run on Ubuntu Linux. Free software purists often argue the average Linux operating system should be called «GNU/Linux» because it’s really a lot of GNU software running on the Linux kernel. The Bash shell you’ll get is really just all those GNU utilities and other software.

While this feature was originally called «Bash on Ubuntu on Windows,» it also allows you to run Zsh and other command-line shells. It now supports other Linux distributions, too. You can choose openSUSE Leap or SUSE Enterprise Server instead of Ubuntu, and there is a remix of Fedora available.

There are some limitations here. It won’t officially work with graphical Linux desktop applications. Not every command-line application works, either, as the feature isn’t perfect.

How Windows Subsystem for Linux 2 (WSL2) Works

Windows Subsystem for Linux 2 (WSL2) is designed to provide the exact same user experience as its predecessor, but the similarities mostly end there.

WSL2 runs a full Linux Kernel in an extremely efficient virtual machine. Just like WSL1, WSL2 allows you use a range of different Linux Distros including, Ubuntu, Debian, Kali, openSUSE, Fedora, and others. That also means that most any Linux application, package, or command will work without an issue.

WSL2 supports GUI applications on Windows 11.

How to Install Bash on Windows 10

This feature doesn’t work on the 32-bit version of Windows 10, so ensure you’re using the 64-bit version of Windows. It’s time to switch to the 64-bit version of Windows 10 if you’re still using the 32-bit version, anyway.

Assuming you have 64-bit Windows, to get started, head to Control Panel > Programs > Turn Windows Features On Or Off. Enable the «Windows Subsystem for Linux» option in the list, and then click the «OK» button.

Open up the Windows Features menu, scroll down until you find "Windows Subsystem for Linux," then tick the box and click "OK."

Click «Restart now» when you’re prompted to restart your computer. The feature won’t work until you reboot.

Starting with the Fall Creators Update, you no longer have to enable Developer Mode in the Settings app to use this feature. You just need to install it from the Windows Features window.

Alternatively, you can also install it using PowerShell. Launch PowerShell as an Administrator, then enter:

wsl --install

It’ll take a few minutes to download and install all of the required components — after it does, you need to restart your computer.

PowerShell running WSL install command successfully.

After your computer restarts, open the Microsoft Store from the Start menu, and search for «Linux» in the store.

Starting with the Fall Creators Update, you can no longer install Ubuntu by running the «bash» command. Instead, you have to install Ubuntu or another Linux distribution from the Store app or using the wsl --install -d <Distribution> command.

Search

You’ll see a list of every Linux distribution currently available in the Windows Store. As of the Fall Creators Update, this includes Ubuntu, openSUSE Leap, and openSUSE Enterprise, with a promise that Fedora will arrive soon.

Debian, Kali, and a remix of Fedora are now available in the Store. Search for «Debian Linux,» «Kali Linux,» or «Fedora Linux» to find and install them.

To install a Linux distribution, click it, and then click the «Get» or «Install» button to install it like any other Store application.

If you’re not sure which Linux environment to install, we recommend Ubuntu. This popular Linux distribution was previously the only option available, but other Linux systems are now available for people who have more specific needs.

Click

You can also install multiple Linux distributions and they’ll each get their own unique shortcuts. You can even run multiple different Linux distributions at a time in different windows.

How to Use The Bash Shell and Install Linux Software

You now have a full command-line bash shell based on Ubuntu, or whatever other Linux distribution you installed.

Because they’re the same binaries, you can use Ubuntu’s apt or apt-get command to install software from Ubuntu’s repositories if you’re using Ubuntu. Just use whatever command you’d normally use on that Linux distribution. You’ll have access to all the Linux command line software out there, although some applications may not yet work perfectly.

To open the Linux environment you installed, just open the Start menu and search for whatever distribution you installed. For example, if you installed Ubuntu, launch the Ubuntu shortcut.

You can pin this application shortcut to your Start menu, taskbar, or desktop for easier access.

Open the Start Menu, type

The first time you launch the Linux environment, you’re be prompted to enter a UNIX username and password. These don’t have to match your Windows username and password, but will be used within the Linux environment.

For example, if you enter «bob» and «letmein» as your credentials, your username in the Linux environment will be «bob» and the password you use inside the Linux environment will be «letmein» — no matter what your Windows username and password are.

Enter a username and password for your Linux distro.

You can launch your installed Linux environment by running the wsl command. If you have multiple Linux distributions installed, you can choose the default Linux environment this command launches.

If you have Ubuntu installed, you can also run the ubuntu command to install it. For openSUSE Leap 42, use  opensuse-42 . For SUSE Linux Enterprise Sever 12, use sles-12 . These commands are listed on each Linux distribution’s page on the Windows Store.

You can still launch your default Linux environment by running the bash command, but Microsoft says this is deprecated. This means the bash command may stop functioning in the future.

Running "bash" in the Command Prompt will launch your default Linux environment.

If you’re experienced using a Bash shell on Linux, Mac OS X, or other platforms, you’ll be right at home.

On Ubuntu, you need to prefix a command with  sudo to run it with root permissions. The «root» user on UNIX platforms has full system access, like the «Administrator» user on Windows. Your Windows file system is located at /mnt/c in the Bash shell environment.

Use the same Linux terminal commands you’d use to get around. If you’re used to the standard Windows Command Prompt with its DOS commands, here are a few basic commands common to both Bash and Windows:

  • Change Directory: cd in Bash, cd or  chdir in DOS
  • List Contents of Directory:  ls in Bash, dir in DOS
  • Move or Rename a File: mv in Bash, move and  rename in DOS
  • Copy a File: cp in Bash,  copy in DOS
  • Delete a File: rm in Bash,  del or erase in DOS
  • Create a Directory:  mkdir in Bash, mkdir in DOS
  • Use a Text Editor: vi or nano in Bash,  edit in DOS

It’s important to remember that, unlike Windows, the Bash shell and its Linux-imitating environment are case-sensitive. In other words, «File.txt» with a capital letter is different from «file.txt» without a capital.

For more instructions, consult our beginner’s guide to the Linux command-line and other similar introductions to the Bash shell, Ubuntu command line, and Linux terminal online.

The command "ls" run in the C:\ directory to list files and folders.

You’ll need to use the apt command to install and update the Ubuntu environment’s software.  Be sure to prefix these commands with sudo , which makes them run as root—the Linux equivalent of Administrator. Here are the apt-get commands you’ll need to know:

  • Download Updated Information About Available Packages: sudo apt update
  • Install an Application Package:  sudo apt install packagename (Replace «packagename» with the package’s name.)
  • Uninstall an Application Package:  sudo apt remove packagename (Replace «packagename» with the package’s name.)
  • Search for Available Packages:  sudo apt search word (Replace «word» with a word you want to search package names and descriptions for.)
  • Download and Install the Latest Versions of Your Installed Packages: sudo apt upgrade

If you installed a SUSE Linux distribution, you can use the zypper command to install software instead.

After you’ve downloaded and installed an application, you can type its name at the prompt, and then press Enter to run it. Check that particular application’s documentation for more details.

Installing GNU Compiler Collection with apt.

Bonus: Install the Ubuntu Font for a True Ubuntu Experience

If you want a more accurate Ubuntu experience on Windows 10, you can also install the Ubuntu fonts and enable them in the terminal. You don’t have to do this, as the default Windows command prompt font looks pretty good to us, but it’s an option.

Here’s what it looks like:

The default font, Consolas.

To install the font, first download the Ubuntu Font Family from Ubuntu’s website. Open the downloaded .zip file and locate the «UbuntuMono-R.ttf» file. This is the Ubuntu monospace font, which is the only one used in the terminal. It’s the only font you need to install.

Open the font ZIP file, then double-click the font you want to preview or install.

Double-click the «UbuntuMono-R.ttf» file and you’ll see a preview of the font. Click «Install» to install it to your system.

Click "Install" near the top if you want to use the font.

To make the Ubuntu monospace font become an option in the console, you’ll need to add a setting to the Windows registry.

Open a registry editor by pressing Windows+R on your keyboard, typing regedit , and then pressing Enter. Navigate to the following key or copy and paste it into the Registry Editor’s address bar:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont
Navigate to the "TrueTypeFont" key.

Right-click in the right pane and select New > String Value. Name the new value 000 .

Double-click the «000» string you just created, and then enter Ubuntu Mono as its value data.

Create a new string named "000", then set the value to "Ubuntu Mono".

Launch an Ubuntu window, right-click the title bar, and then select the «Properties» command. Click the «Font» tab, and then select «Ubuntu Mono» in the font list.

Right-click the title bar of the terminal application you're using, go to "Properties," then click "Font." Select "Ubuntu Mono" from the list.

Software you install in the Bash shell is restricted to the Bash shell. You can access these programs from the Command Prompt, PowerShell, or elsewhere in Windows, but only if you run the bash -c command.

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

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

Что такое WSL?

В начале цикла разработки Windows 10, Microsoft открыла страницу обсуждения и голосования за новые функции. Там зашел разговор о командной строке Windows. Разработчики спросили сообщество, что им не нравится в командной строке Windows и какие функции они хотели бы увидеть в новой версии.

Многие пользователи заявили что им нужны небольшие улучшения командной строки, другие же сказали что неплохо было бы иметь возможность использовать инструменты Linux / Unix и Bash в Windows 10. Много пользователей согласились с тем, что нужно сделать проще использование этих инструментов в Windows.

Прислушиваясь к голосу сообщества, в Microsoft первым делом улучшили CMD, PowerShell и другие инструменты командной строки. А во-вторых, они сделали, то что казалось невероятным несколько лет назад, они добавили реальный, нативный Bash вместе с поддержкой всех необходимых инструментов командной строки, работающих непосредственно на Windows, в среде, которая ведет себя как Linux. Это не какая-нибудь виртуальная машина, это реальный Linux в Windows.

Для реализации этого Microsoft построили новую инфраструктуру в Windows, это Windows Subsystem for Linux или WSL, на основе которой работает образ окружения Ubuntu, поставляемый партнером Canonical. Эта функция позволит разработчикам более эффективно использовать инструменты Linux. Инфраструктура основана на уже заброшенном проекте, Project Astoria, который должен был использоваться для запуска Android-приложений в Windows. Ее можно расценивать как противоположность Wine, только Wine запускает приложения Windows в Linux, подсистема Linux позволяет выполнять приложения Linux в Windows, точнее, только консольные приложения Bash в Windows 10.

С технической точки зрения, это вообще не Линукс. Каждая система GNU Linux должна быть основана на ядре Linux, здесь же просто есть возможность выполнять двоичные файлы, которые работают в Ubuntu.

С каждой новой версией  в WSL всё меньше ограничений, вы уже можете использовать сервисы, а также с WSL 2 стали доступны графические приложения. Решение предназначено для разработчиков, которые хотят запускать linux-утилиты из командной строки Windows. Да, эти команды имеют доступ к файловой системе Windows, но вы не можете использовать их для автоматизации своих задач или в стандартной командной строке Windows. Теперь давайте разберемся как установить WSL в Windows 10.

1. Проверка версии системы

Вы можете установить WSL в Windows 10 начиная с версии Windows 10 Insider Preview 14316, а для WSL версии 2, которая принесла много улучшений нужно обновление Windows 10 19041 или новее. Сначала убедитесь, что у вас правильная версия Windows. Для этого октройте PowerShell кликнув правой кнопкой по иконке пуск:

Затем выполните команду:

[environment]::osversion

Если отображается версия как на снимке экрана или выше, значит всё хорошо. Иначе идите обновлять систему.

2. Активация WSL и виртуализации

Чтобы активировать компонент Windows Subsystem for Linux можно использовать уже открытую командную строку PowerShell. Для этого выполните:

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

Затем выполните ещё одну команду чтобы включить компонент виртуализации Hyper-V:

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

Когда эта работа будет выполнена перезапустите компьютер, чтобы все компоненты установились.

3. Активация WSL 2

Чтобы установить WSL 2 необходимо скачать пакет с новым ядром с официального сайта Microsoft. Кликните по ссылке download the latest WSL2 Linux kernel:

Затем установите загруженный файл:

Чтобы всегда по умолчанию использовалась версия WSL 2 необходимо выполнить такую команду:

wsl --set-default-version 2

Если вы всё же получаете ошибку, с сообщением о том, что такой опции у этой команды нет, значит у вас старая версия Windows, обновляйте. Если команда не выдала ошибки — значит настройка WSL завершена успешно.

4. Установка Linux

Далее вам надо установить какой-либо дистрибутив Linux из магазина Microsoft. Достаточно просто открыть магазин и набарть в поиске имя дистрибутива, например Ubuntu, затем нажмите кнопку Get:

Дождитесь завершения установки и запустите загруженный дистрибутив из главного меню:

5. Настройка дистрибутива

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

Затем два раза пароль:

После этого вы сможете пользоваться оболочкой Bash в Windows 10:

6. Установка X сервера

Если вы хотите запускать графические приложения из WSL Windows, то вам понадобится установить в систему X сервер. Скачать его можно здесь.

Затем просто установите.

7. Запуск X сервера

После завершения установки на рабочем столе появится ярлык. В первом окне выберите Multipe windows чтобы окна программ, выполняемых на X сервере интегрировались в систему:

Затем выберите, что клиентов запускать не надо — Start no client:

Поставьте все галочки, затем нажмите кнопку Next, а потом Finish для завершения установки.

Брандмауэр Windows тоже попросит разрешить доступ этому приложению в сеть. Надо разрешить.

8. Настройка подключения

Чтобы настроить подключение к X серверу из WSL нужно узнать какой адрес система Windows присвоила WSL окружению, для этого вернитесь к PowerShell и выполните:

ipconfig

В данном случае это 172.25.224.1. Выполните в окружении дистрибутива такую команду:

export DISPLAY=172.25.224.1:0

Шаг 9. Установка и запуск приложений

Для установки приложений в дистрибутив необходимо сначала обновить списки репозиториев:

sudo apt update

Затем установите графическое приложение, например, Firefox:

sudo apt install firefox

После этого его можно запустить:

firefox

На снимке вы видите графический интерфейс WSL для браузера Firefox, запущенного в Linux:

Использование WSL

Установка WSL Windows 10 завершена. Теперь у вас есть полноценная командная строка Ubuntu в Windows с оболочкой Bash. Поскольку используются одни и те же двоичные файлы, вы можете устанавливать программное обеспечение с помощью apt из репозиториев Ubuntu. Можно установить любое приложение, но не все будут работать.

Если вы раньше уже пользовались Bash в Linux или MacOS, то будете чувствовать себя здесь как дома. Здесь не нужно использовать команду sudo, поскольку у оболочки уже есть права администратора. Ваша файловая система Windows доступна в /mnt/c.

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

  • cd — изменить текущий каталог;
  • ls — посмотреть содержимое каталога;
  • mv — переместить или переименовать файл;
  • cp — скопировать файл;
  • rm — удалить файл;
  • mkdir — создать папку;
  • vi или nano — открыть файл для редактирования.

Важно также понимать, что в отличии от WIndows, оболочка Bash и ее окружение чувствительны к регистру. Другими словами, file.txt и File.txt, это совсем разные файлы.

Для установки и обновления программ необходимо использовать команду apt-get. Вот небольшой список ее  параметров:

  • apt update — скачать списки программного обеспечения из репозиториев;
  • apt install пакет — установить пакет;
  • apt search слово — поиск пакета по слову;
  • apt upgrade — загрузка и установка последних обновлений дистрибутива.

Не забудьте, что устанавливаемые в этой оболочке программы, ограничиваются по области действия оболочкой. Вы не можете получить доступ к ним из обычной командной строки PowerShell, CMD или в любом другом месте Windows. Также WSL не может напрямую взаимодействовать с исполняемыми файлами Windows, хотя обе среды имеют доступ к одним и тем же файлам на компьютере.

Выводы

Использование Linux в Windows как нельзя лучше подойдёт для разработчиков, но может понадобиться и начинающим пользователям, которые хотят познакомиться с системой. А что вы обо всём этом думаете? Использовали ли когда-нибудь WSL? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Нужно использовать терминал Linux на компьютере с Windows? Узнайте, как запустить Linux на Windows 10 с помощью Windows Subsystem for Linux.

Хотите получить быстрый и простой доступ к Linux на ПК с Windows? Лучший вариант – использовать подсистему Windows Subsystem for Linux.

Это даст вам оболочку Linux bash, окно терминала, запущенное в Windows. Этот процесс, по сути, устанавливает Linux на Windows 10 – вот что вам нужно знать.

Впервые появившись в обновлении Windows 10 Anniversary Update 2018 года и распространившись среди всех пользователей в обновлении Fall Creators Update, подсистема Windows для Linux позволяет запускать программное обеспечение Linux в Windows 10.

Это функция, которая была встроена в Windows. В отличие от установки Linux на виртуальной машине, Windows Subsystem for Linux может быть мгновенно вызвана из меню “Пуск”.

Однако для того, чтобы это работало, необходимо сначала включить эту функцию.

После установки подсистемы Windows для Linux в Windows 10 вы можете запускать Linux в режиме командной строки. Это дает вам почти полнофункциональный терминал Linux для Windows 10.

Linux Bash Shell: Только для 64-разрядных версий Windows 10

Прежде чем приступить к работе, убедитесь, что вы используете 64-разрядную версию Windows 10. К сожалению, подсистема Windows для Linux не будет работать на 32-битных системах. Проверьте, работает ли на вашем компьютере 32- или 64-разрядная версия Windows.

Чтобы проверить компьютер на 64-битную совместимость, нажмите WIN + I, чтобы открыть “Настройки”, затем “Система” > “О системе”. В разделе “Характеристики устройств” вы увидите список “Тип системы”; для Windows Subsystem for Linux у вас должно показать 64-битную операционную систему.

muo windows wsl 64 bit

Проверьте, является ли ваш компьютер 64-разрядным

Если нет, вам нужно обновить систему Windows 10 с 32-разрядной до 64-разрядной. Однако это сработает только в том случае, если у вас 64-битное оборудование.

Как установить Linux Bash Shell на Windows 10

Прежде чем продолжить, учтите, что в некоторых системах не могут быть одновременно включены подсистема Windows для Linux и виртуальные машины (VM). Поэтому, если вы предпочитаете запускать Linux в виртуальной машине, вам нужно будет отключить Windows Subsystem for Linux, прежде чем снова использовать виртуальную машину.

Готовы установить Bash в Windows? Начните с нажатия кнопки Пуск и ввода “Включение или отключение компонентов Windows“. Должен появиться пункт Включение или отключение компонентов Windows, щелкните его, чтобы открыть. Подождите, пока список заполнится, затем прокрутите вниз до пункта Подсистема Windows для Linux.

Этот флажок должен быть отмечен. Если его нет, добавьте галочку и нажмите OK для подтверждения.

windows wsl add feature

Включить подсистему Windows для Linux

Вам будет предложено перезапустить Windows, поэтому следуйте этой инструкции. После перезагрузки откройте Пуск > Магазин Windows. С помощью инструмента поиска найдите записи, относящиеся к “Linux”, и выберите предпочтительную версию Linux для установки. От того, какую версию вы выберете, будет зависеть работа с Bash. Например, вы можете установить Ubuntu на Windows 10.

windows wsl store

Дистрибутивы Linux в Магазине Windows

Установите операционную систему Linux, затем подождите. После завершения нажмите кнопку Запуск в Магазине Windows или откройте его из меню Пуск. При первом запуске вам будет предложено ввести имя пользователя и пароль для создания учетной записи.

Для запуска выбранной вами среды Linux доступны и другие способы. В меню “Пуск” вы можете ввести:

  • bash
  • wsl

Оба способа отобразятся как “Выполнить команду”, которую можно выбрать для мгновенного открытия оболочки Bash. Разница в использовании любого из этих методов заключается в том, что они открываются в каталоге /mnt/c/Windows/System32. Это означает, что вы можете просматривать подкаталог System32 в Windows 10.

Linux в Windows

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

Кроме того, для запуска Bash больше не нужно включать режим разработчика Windows 10 в Настройках.

Чем отличается терминал Bash Shell от Windows PowerShell?

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

Но чем это отличается от простого использования командной строки Windows или PowerShell?

Ну, естественно, обе системы совершенно разные. При использовании PowerShell или командной строки вы ограничены командами, характерными для Windows. Это означает, например, использование команды dir для просмотра содержимого каталога; в Linux эквивалентом является ls.

В принципе, различия между Windows и Linux – это то, что отличает эти две текстовые среды. Преимущество наличия оболочки Bash в Windows 10 заключается в том, что вы можете легко получить доступ к Linux в Windows. Это экономит время на настройку виртуальной машины или перезагрузку при установке Linux с двойной загрузкой.

Что можно делать с Bash в Windows 10?

Установив оболочку Bash в Windows 10, вы можете использовать ее так же, как и на ПК с Linux.

Стандартные команды, такие как help, покажут вам, как пользоваться предустановленными приложениями и инструментами. Например, apt help продемонстрирует использование менеджера пакетов. Вы можете использовать sudo apt update для получения последних пакетов, как и на ПК с Linux.

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

Аналогично, команда sudo apt upgrade обновляет Linux до последней версии ОС.

Между тем, доступны и другие стандартные команды. Вы можете проверить подключение к сети с помощью ifconfig, проверить текущий каталог с помощью pwd и перейти в другой каталог с помощью cd.

Вы также можете получить быстрый список последних 10 вводов с помощью команды history.

Одним словом, это все равно что использовать Linux в операционной системе Windows 10.

Windows 10 Bash приносит Linux на любой компьютер

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

Вкратце, все, что вам нужно сделать для запуска оболочки Linux Bash на Windows 10, это:

  • Убедитесь, что вы используете 64-разрядную Windows 10.
  • Включить подсистему Windows для Linux на экране Windows Features.
  • Установите выбранную вами среду Linux из Магазина Windows.
  • Запустите Linux из меню “Пуск”.

После этого вы можете использовать терминал Linux для Windows для стандартных задач командной строки. Или вы можете использовать подсистему Linux в Windows 10 для установки среды рабочего стола.

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

В следующей статье, мы рассмотрим как установить рабочее окружение lmde, xfce или kde в wls.

Как запустить рабочий стол Linux в Windows с помощью WSL

  • Bamboo cth 670 драйвер windows 10
  • Baseus bluetooth adapter драйвер windows 10
  • B85m g драйвера для windows 10
  • Bad system config info windows server 2019
  • B450 windows 7 usb driver