Как использовать bash в windows 10

В 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).

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

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

50

50 people found this article helpful

Use the Linux command line in Windows

What to Know

  • Developer Mode: Right-click Start menu > select Settings > Update & Security > For developers.
  • Next: Select Developer mode > Yes > enable Windows Subsystem For Linux > restart.
  • Use bash: Right-click Start menu > select Windows PowerShell (Admin) > type «bash» > press Enter.

This article explains how to install and setup bash to use Linux commands on the 64-bit version of Windows 10.

okubax / Flickr

How to Turn on Windows Developer Mode

To enable developer functions for Windows:

  1. Right-click the Start menu and select Settings.

  2. Select Update & Security.

  3. Select For developers on the left side.

  4. Select Developer mode.

  5. Select Yes to confirm, then wait for the developer package to install.

  6. Type Windows Features in the desktop search bar and select Turn Windows Features On Or Off.

  7. Check the box beside Windows Subsystem For Linux and select OK.

  8. Select Restart now in the dialog box to reboot your computer to apply the changes.

How to Use Bash in Windows

After your computer reboots, you’re ready to set up bash for Windows:

  1. Go to the Microsoft Store and select the Linux distribution of your choice. Install it then launch it.

  2. Wait for the distribution to finish installing, then create a username in the command window and press Enter. During the first-run process, you’ll have to engage in some basic configuration, depending on the distribution. Often, you must specify a username and password.

  3. After the installation is successful, close the window and right-click the Start menu, then select Windows PowerShell (Admin).

  4. Type bash in the terminal window and press Enter.

You now have a core version of Ubuntu installed on your system without any graphical desktops or subsystem. Therefore, you can now use Linux commands to communicate with the Windows file structure. Anytime you want to run the Linux command line, open the PowerShell or the command prompt and enter bash.

What You Need to Install Bash on Windows

To run bash, your computer needs to be running a 64-bit version of Windows with a version number no lower than 14393, so update Windows 10 to the latest version before you begin. In order to run the Linux shell, you need to turn on Windows developer mode and enable the Linux subsystem.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

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

  • Install the Ubuntu Font for a True Ubuntu Experience

  • Use the Ubuntu Monospace Font in the Console

  • Use the Ubuntu Monospace Font in the Terminal

Summary

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.

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.

Linux distros available on the Microsoft Store.

You’ll see a list of every Linux distribution currently available in the Windows Store.This includes Ubuntu, openSUSE Leap, and openSUSE Enterprise, Debian, Kali, and others. You can even find a few remixes of Fedora, though there isn’t an official version available as of November 2023.

If you want a specific distro, search for that rather than «Linux.» You’ll get better results.

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.

Installing Debian through the Microsoft Store.

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 through Ubuntu, or whichever 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.

Searching for "Ubuntu" in the Start Menu.

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.

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.

Use the Ubuntu Monospace Font in the Console

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.

Use the Ubuntu Monospace Font in the Terminal

If you’re using the Windows Terminal—and you should be, it is a big improvement in most ways—changing fonts is easier. After you’ve installed the Ubuntu font, open up the Terminal, click the small downward facing arrow, and select «Settings.»

Open the Terminal Settings.

Open to Defaults > Appearance, then select «Ubuntu Mono» from the list of available fonts.

The Terminal automatically expands or collapses the labels in the left sidebar depending on the size of your window, much like the Settings app does. You may not see the «Default» text label depending on the size of your window.

Enable the Ubuntu Mono font.

Remember: 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.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как удалить музыку с компьютера windows 10
  • Как узнать работает ли звуковая карта на компьютере windows 10
  • Как сменить экран загрузки windows 10
  • Код ошибки 0x8000000b windows 10 как исправить
  • Код 8024402f центра обновления windows 7