Windows subsystem for linux command reference скачать

Source code behind the Windows Subsystem for Linux documentation. - WSL/basic-commands.md at main · MicrosoftDocs/WSL
title description ms.date ms.topic

Basic commands for WSL

Reference for the basic commands included with Windows Subsystem for Linux (WSL).

11/16/2022

article

Basic commands for WSL

The WSL commands below are listed in a format supported by PowerShell or Windows Command Prompt. To run these commands from a Bash / Linux distribution command line, you must replace wsl with wsl.exe. For a full list of commands, run wsl --help.

Install

Install WSL and the default Ubuntu distribution of Linux. Learn more. You can also use this command to install additional Linux distributions by running wsl --install <Distribution Name>. For a valid list of distribution names, run wsl --list --online.

Options include:

  • --distribution: Specify the Linux distribution to install. You can find available distributions by running wsl --list --online.
  • --no-launch: Install the Linux distribution but do not launch it automatically.
  • --web-download: Install from an online source rather than using the Microsoft Store.

When WSL is not installed options include:

  • --inbox: Installs WSL using the Windows component instead of using the Microsoft Store. (WSL updates will be received via Windows updates, rather than pushed out as-available via the store).
  • --enable-wsl1: Enables WSL 1 during the install of the Microsoft Store version of WSL by also enabling the «Windows Subsystem for Linux» optional component.
  • --no-distribution: Do not install a distribution when installing WSL.

List available Linux distributions

See a list of the Linux distributions available through the online store. This command can also be entered as: wsl -l -o.

List installed Linux distributions

See a list of the Linux distributions installed on your Windows machine, including the state (whether the distribution is running or stopped) and the version of WSL running the distribution (WSL 1 or WSL 2). Comparing WSL 1 and WSL 2. This command can also be entered as: wsl -l -v. Additional options that can be used with the list command include: --all to list all distributions, --running to list only distributions that are currently running, or --quiet to only show distribution names.

Set WSL version to 1 or 2

wsl --set-version <distribution name> <versionNumber>

To designate the version of WSL (1 or 2) that a Linux distribution is running on, replace <distribution name> with the name of the distribution and replace <versionNumber> with 1 or 2. Comparing WSL 1 and WSL 2.

Set default WSL version

wsl --set-default-version <Version>

To set a default version of WSL 1 or WSL 2, replacing <Version> with either the number 1 or 2 to represent which version of WSL you would like the installation to default on for new Linux distribution installations. For example, wsl --set-default-version 2. Comparing WSL 1 and WSL 2.

Set default Linux distribution

wsl --set-default <Distribution Name>

To set the default Linux distribution that WSL commands will use to run, replace <Distribution Name> with the name of your preferred Linux distribution.

Change directory to home

The ~ can be used with wsl to start in the user’s home directory. To jump from any directory back to home from within a WSL command prompt, you can use the command: cd ~.

Run a specific Linux distribution from PowerShell or CMD

wsl --distribution <Distribution Name> --user <User Name>

To run a specific Linux distribution with a specific user, replace <Distribution Name> with the name of your preferred Linux distribution (ie. Debian) and <User Name> with the name of an existing user (ie. root). If the user doesn’t exist in the WSL distribution, you will receive an error. To print the current user name, use the command whoami.

Update WSL

Update your WSL version to the latest version. Options include:

  • --web-download: Download the latest update from the GitHub rather than the Microsoft Store.

Check WSL status

See general information about your WSL configuration, such as default distribution type, default distribution, and kernel version.

Check WSL version

Check the version information about WSL and its components.

Help command

See a list of options and commands available with WSL.

Run as a specific user

wsl -u <Username>`, `wsl --user <Username>

To run WSL as a specified user, replace <Username> with the name of a user that exists in the WSL distribution.

Change the default user for a distribution

<DistributionName> config --default-user <Username>

Change the default user for your distribution log-in. The user has to already exist inside the distribution in order to become the default user.

For example:
ubuntu config --default-user johndoe would change the default user for the Ubuntu distribution to the «johndoe» user.

[!NOTE]
If you are having trouble figuring out the name of your distribution, use the command wsl -l.

[!WARNING]
This command will not work for imported distributions, because these distributions do not have an executable launcher. You can instead change the default user for imported distributions using the /etc/wsl.conf file. See the Automount options in the Advanced Settings Configuration doc.

Shutdown

Immediately terminates all running distributions and the WSL 2 lightweight utility virtual machine. This command may be necessary in instances that require you to restart the WSL 2 virtual machine environment, such as changing memory usage limits or making a change to your .wslconfig file.

Terminate

wsl --terminate <Distribution Name>

To terminate the specified distribution, or stop it from running, replace <Distribution Name> with the name of the targeted distribution.

Import and export a distribution

wsl --export <Distribution Name> <FileName>
wsl --import <Distribution Name> <InstallLocation> <FileName>

Imports and exports the specified tar file as a new distribution. The filename can be — for standard input. Options include:

  • --vhd: Specifies the import/export distribution should be a .vhdx file instead of a tar file
  • --version: For import only, specifies whether to import the distribution as a WSL 1 or WSL 2 distribution

Import a distribution in place

wsl --import-in-place <Distribution Name> <FileName>

Imports the specified .vhdx file as a new distribution. The virtual hard disk must be formatted in the ext4 filesystem type.

Unregister or uninstall a Linux distribution

While Linux distributions can be installed through the Microsoft Store, they can’t be uninstalled through the store.

To unregister and uninstall a WSL distribution:

wsl --unregister <DistributionName>

Replacing <DistributionName> with the name of your targeted Linux distribution will unregister that distribution from WSL so it can be reinstalled or cleaned up. Caution: Once unregistered, all data, settings, and software associated with that distribution will be permanently lost. Reinstalling from the store will install a clean copy of the distribution. For example, wsl --unregister Ubuntu would remove Ubuntu from the distributions available in WSL. Running wsl --list will reveal that it is no longer listed.

You can also uninstall the Linux distribution app on your Windows machine just like any other store application. To reinstall, find the distribution in the Microsoft Store and select «Launch».

Mount a disk or device

Attach and mount a physical disk in all WSL2 distributions by replacing <DiskPath> with the directoryfile path where the disk is located. See Mount a Linux disk in WSL 2. Options include:

  • --vhd: Specifies that <Disk> refers to a virtual hard disk.
  • --name: Mount the disk using a custom name for the mountpoint
  • --bare: Attach the disk to WSL2, but don’t mount it.
  • --type <Filesystem>: Filesystem type to use when mounting a disk, if not specified defaults to ext4. This command can also be entered as: wsl --mount -t <Filesystem>.You can detect the filesystem type using the command: blkid <BlockDevice>, for example: blkid <dev/sdb1>.
  • --partition <Partition Number>: Index number of the partition to mount, if not specified defaults to the whole disk.
  • --options <MountOptions>: There are some filesystem-specific options that can be included when mounting a disk. For example, ext4 mount options like: wsl --mount -o "data-ordered" or wsl --mount -o "data=writeback. However, only filesystem-specific options are supported at this time. Generic options, such as ro, rw, or noatime, are not supported.

[!NOTE]
If you’re running a 32-bit process in order to access wsl.exe (a 64-bit tool), you may need to run the command in the following manner: C:WindowsSysnativewsl.exe --command.

Unmount disks

Unmount a disk given at the disk path, if no disk path is given then this command will unmount and detach ALL mounted disks.

Deprecated WSL commands

wslconfig.exe [Argument] [Options]

These commands were the original wsl syntax for configuring Linux distributions installed with WSL, but have been replaced with the wsl or wsl.exe command syntax.

Windows Subsystem for Linux (WSL) — подсистема ОС Windows 10, позволяющая разработчикам, тестировщикам запускать нативные приложения Linux, писать скрипты, выполнять команды непосредственно из Windows. В обновлённой Windows 10 (2004) появилась 2я версия WSL, в которой используется полноценное ядро Linux с возможностью запуска приложений и контейнеров Docker, реализована высокая скорость загрузки, небольшой объем потребляемых ресурсов, управление в фоновом режиме, обновление ядра. Таким образом вы сможете запускать ELF64 программы, которые могут получать доступ к файловой системе Windows без использования сторонних порто (таких как Cygwin).

Образ ядра Linux (версия ядра 4.19) в Windows 10 представляет собой легкую виртуальную машину, для запуска которой не нужно ставить полноценную роль Hyper-V. Системные вызовы Linux транслируются на лету в вызовы Windows без использования эмулятора (в отличии от WSL1).

Изначально компонент WSL отключен. Чтобы его включить, вам необходимо зайти в Пуск -> Панель управления -> Программы и компоненты -> Включение и отключение компонентов Windows (Control PanelAll Control Panel ItemsPrograms and FeaturesTurn Windows features on or off), активировать галочку Подсистема Windows для Linux (Windows Subsystem for Linux), нажать кнопку ОК, и перезагрузить компьютер.

установка Windows Subsystem for LInux 2 версия в windows 10

Вы можете включить компоненты WSL в Windows 10 с помощью dism:

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

или PowerShell

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

В Windows Server 2004 Semi-Annual Channel (SAC) для установки компонента WSL используется командлет Install-WindowsFeature:

Install-WindowsFeature -Name Microsoft-Windows-Subsystem-Linux

После этого также необходимо перезагрузить компьютер.

В настройка BIOS/UEFI компьютера должна быть включена поддержка аппаратной виртуализации: Intel VT (Intel Virtualization Technology) или AMD-V.

Теперь вам нужно выполнить обновление WSL до версии 2. Для этого требуется зайти на сайт https://docs.microsoft.com/ru-ru/windows/wsl/wsl2-kernel, скачать файл wsl_update_x64.msi, установить его. По завершении увидите картинку

windows subsyste for linux update setup

Чтобы сделать WSL2 архитектурой по умолчанию для новых дистрибутивов, в PowerShell выполните команду:

wsl --set-default-version 2

Далее вам необходимо открыть Microsoft Store, в поиске ввести слово “Linux”. В появившемся списке выберите нужный дистрибутив. Доступные Ubuntu, Debian, Kali Linux, Linux Cheatsheet, SUSE Linux Enterprise Server15, openSUSE Leap 15-1, Pengwin Enterprise, Fedora Remix for WSL или другие. В нашем примере мы будем использовать Ubuntu 20.04 LTS, нажмите кнопку Получить.

образы linux для wsl в microsoft store

Если у вас отключен Windows Store или вы хотите установить дистрибутив WSL в Core редакции Windows Server, вы можете скачать дистрибутив Ubuntu с помощью PowerShell командлета Invoke-WebRequest:

Invoke-WebRequest https://aka.ms/wslubuntu2004 -OutFile ubuntu-2004.zip –UseBasicParsing

Распакуйте архив:

Expand-Archive -Path .ubuntu-2004.zip

Запустите установку образа Linux с помощью файла Ubuntu.exe.

Также вы можете скачать образ в виде appx файла и установить его с помощью командлета Add-AppxPackage.

После установки можно проверить используемую версию WSL с помощью команды

wsl --list –-verbose

wsl --list –-verbose список доступных образов linux

Если у вашей среды Linux указана версия 1, нужно изменить ее на WSL2 командой:

wsl --set-version Ubuntu-20.04 2

Файл жёсткого диска с образом виртуальной машины ОС Linux Ubuntu 20.04 будет располагаться в профиле пользователя: C:Users234AppDataLocalPackagesCanonicalGroupLimited.Ubuntu20.04onWindows_79rhkp1fndgscLocalState.

После установки дистрибутива в стартовом меню появляется ярлык на него. Для запуска Ubuntu зайдите в меню Пуск, нажмите на соответствующем ярлыке и получите в отдельном окне полноценную командную оболочку Bash. Запускать WSL можно и с помощью команды wsl. При первом запуске образа в командной строке Bash вам будет предложено создать пользователя и пароль (которые не должны совпадать с учётной записью Windows). Чтобы выполнять команды с правами root, необходимо использовать дополнительный ключ (префикс) sudo. В WSL есть общие команды для Bash и CMD, и тут нужно не забывать, что система Linux чувствительна к регистру.

Вы можете выполнить Linux-команды из CMD. Для этого необходимо вначале указать “WSL”. Например, для просмотра списка файлов и папок в каталоге Windows, выполните:

wsl
ls /mnt
ls/mnt/c

запуск команд linux в windows
dir | wsl grep Sa
wsl ls ‑la > 123.txt
wsl ls ‑la /proc/cpuinfo
wsl ls ‑la “/mnt/c/Program Files”

команды linux

Также вы можете открыть проводник командой explorer.exe, калькулятор – calc.exe, блокнот – notepad.exe, paint – mspaint.exe, календарь – cal, погоду – curl wttr.in

запуск команд linux в windows 10 subsystem for linux

Ещё один пример взаимосвязи 2х систем – вы можете открыть в Windows файл из WSL-дистрибутива по сетевому пути. Для этого в CMD наберите путь к файлу:

notepad \wsl$Ubuntu-20.04home1122.txt

Из окна консоли вы можете обновить список пакетов в Ubuntu с помощью команд:

sudo apt-get update
sudo apt-get upgrade

После обновления Ubuntu папка …/LocalState будет занимать 1.5 Гб.

Из командной строки Linux можно не только просмотреть Windows-файлы и каталоги, но и получить к ним доступ. Чтобы удобнее копировать файлы, просматривать директории и их содержимое, установите файловый менеджер Midnight Commander с помощью команды

sudo apt-get install mc

Вы можете запустить Midnight Commander как в командной оболочке Bash, так и внутри CMD. На скриншоте ниже показано, что в двух панелях MC показывается список файлов с обеих ОС.

Midnight Commander в windows 10 wsl2

Можно отобрахить сетевые настройки (IP адрес) IP-адрес Linux-системы:

ip addr | grep eth0

запуск команд linux из windows

В WSL не предусмотрена работа приложений с графическим интерфейсом. Тем не менее вы можете попробовать их установить и использовать. Чтобы запускать графические приложения в Linux, нужно скачать и установить в Windows программу VcXsrv Windows X Server (https://sourceforge.net/projects/vcxsrv/).

VcXsrv Windows X Server

С помощью пакетного менеджера apt-get установим несколько графических программ: например, браузер, текстовый редактор или что-то ещё:

sudo apt-get install gedit
sudo apt-get install firefox
sudo apt-get install x11-app

Затем создайте файл в директории root:

cd /~
vim .bash_login

впишите строку

export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0

сохраните запись

Esc -> :wr -> :q

Теперь можете запустить графические программы Linux через WSL командами:

firefox

или

gedit

запуск браузера firefox через WSL 2 в Windows 10

запуск графического редактора gedit в WSL

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

wsl --list –all

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

wsl --shutdown

In the first chapter of Cybersecurity Ops with bash we go over some of the ways you can leverage the power of the Linux command line directly from the Windows environment.

One of my favorite ways of doing this is by using the Windows Subsystem for Linux or WSL.

WSL was introduced as part of Windows 10, and it allows you to run an emulated or virtualized version of Linux natively within Windows.

There are several Linux distributions to choose from including Ubuntu and Kali.

How to Install WSL in Windows 10

In order to use WSL you will first need to install it.

1. Using the Windows Start Menu, search for «Windows Features»

2. Select «Turn Windows features on or off»

Turn On Windows Feature

Turn On Windows Feature

3. Check the box next to «Windows Subsystem for Linux» and select «OK»

Enable the Windows Subsystem for Linux

Enable the Windows Subsystem for Linux

4. After the installation completes select «Restart now»

5. Once the system is restarted use the Windows Start Menu to search for «Microsoft Store»

6. In the Microsoft Store, search for «Linux» and select the Linux distribution you would like to install

Microsoft Store

Microsoft Store

7. Click the «Install» button and then «Get»

Install Ubuntu

Install Ubuntu

8. After the Linux distribution is done installing click the «Launch» button.

You are now ready to start using the Windows Subsystem for Linux!

For more advance directions and troubleshooting see Microsoft’s instructions.

How to Run WSL

Once the Windows Subsystem for Linux is enabled and you have installed a Linux distribution you can start it by opening the Windows Command Prompt and typing wsl

C:>wsl

Welcome to Ubuntu 20.04.2 LTS (5.4.72-microsoft-standard-WSL2 x86_64)
$

Error Message — No Installed Distributions

Sometimes when running WSL for the first time you may receive the following error:

C:>wsl

Windows Subsystem for Linux has no installed distributions.
Distributions can be installed by visiting the Microsoft Store:

To resolve this, perform a search using the Windows Start Menu for the name of the Linux distribution you installed from the Microsoft Store. For example, search for «Ubuntu»:

Launch WSL Ubuntu Instance

Launch WSL Ubuntu Instance

Click the program to launch it and that should finish the installation on your system. You should not longer receive the error message when running wsl from the Command Prompt.

Once inside the WSL Linux distribution you can do things you normally would such as run Linux commands and install packages.

Running Linux Commands from Within WSL

Running Linux Commands from Within WSL

You can also directly run Linux commands from the Windows Command Prompt by using the wsl command and providing the Linux command as an argument. The command will execute in the WSL Linux distribution and the results will be returned back to the Windows command prompt.

In the example below you can see the Linux cowsay command run directly from the Windows Command Prompt:

Running Linux Commands from the Windows Command Prompt

Running Linux Commands from the Windows Command Prompt

Note that you must precede the Linux command with wsl, if you do not you will receive an error. Here is the incorrect method:

C:>grep

'grep' is not recognized as an internal or external command,
operable program or batch file.

And here is the correct method:

C:>wsl grep

Usage: grep [OPTION]... PATTERNS [FILE]...
Try 'grep --help' for more information.

Piping and Redirection

You can also use input/output piping and redirection when using the wsl command, but you need to be careful how you do it to ensure it occurs within the correct operating system environment. Let’s see what happens if you run the following command pipeline from the Windows command prompt:

C:>wsl ps -e | grep ps

'grep' is not recognized as an internal or external command,
operable program or batch file.

Note that the output states that the grep command is not recognized. That is because Windows executes the ps -e command from within the WSL environment, but then returns the result back to the Windows environment. Windows then tries to pipe that output into the grep command, which of course does not exist in the Windows environment. To overcome this, simply add the wsl command again after the pipe so the grep command runs in the Linux environment.

C:>wsl ps -e | wsl grep ps
    7 tty1     00:00:00 ps

I/O redirection works the same way. Here is an example:

C:>wsl ps -e > ps.txt

Here the ps -e command is executed in the Linux environment using wsl and the results are returned to the Windows environment. Windows then redirects the output to the file ps.txt.

WSL and Windows PowerShell

Running Linux Commands from PowerShell

Running Linux Commands from PowerShell

Running WSL works exactly the same way from the Windows PowerShell. That means you are able to access your favorite Linux commands, bash scripts, and programs from directly within PowerShell scripts!

WSL 2

In mid-2020 Microsoft released WSL version 2. WSL 2 provides a more full-featured virtualized environment allowing for complete access to system calls. That means you can now install the complete array of Linux applications including Docker and similar programs.

Recent releases of WSL also supports running Linux programs that have graphical user interfaces.

Links and Resources

  • Installing WSL

  • Command reference for Windows Subsystem for Linux

  • WSL Version 2

К написанию данной статьи меня побудил вопрос на Тостере, связанный с WSL. Я, после нескольких лет использования систем на ядре Linux, около полугода назад перешел к использованию Windows 10 на домашнем ПК. Зависимость от терминала и Linux окружения в моей работе практически сразу привели меня к вопросу: или ставить виртуалку или попробовать WSL. Я выбрал второе, и остался вполне доволен.

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

Никогда не думал, что однажды вернусь на Windows, но повод попробовать мне дали стечения обстоятельств: жена, далекая от IT, дергала почти каждый раз, когда у нее возникала необходимость воспользоваться компом; проснулась ностальгия по одной игре, но она никак не хотела адекватно работать под wine; а тут еще мне подарили коробочную Windows 10 Pro. WSL я поставил чуть ли не сразу после установки системы, поигрался несколько вечеров, понял, что продукт для моих задач годный, но хочется более привычный терминал и вообще некоторых удобств.

Установка WSL и дистрибутива

Сразу оговорюсь, в интернете можно найти описание установки с помощью выполнения команды lxrun /install в командной строке или консоли PowerShell. Данный способ больше не работает (после выхода WSL в стабильный релиз). Насколько мне известно, сейчас WSL можно установить только из Microsoft Store вместе с предпочитаемым дистрибутивом.

Так же отмечу, что когда установку производил я, на выбор были доступны дистрибутивы OpenSUSE, SUSE Linux Enterprise и Ubuntu 16.04 — последний я и установил. Сейчас также доступны Ubuntu 18.04, Debian 9 и Kali Linux, возможно появятся и другие дистрибутивы. Действия по установке могут отличаться. Так же, часть проблем описанных в статье может быть уже исправлена.

Находим в магазине желаемый дистрибутив и устанавливаем. Установка пройдет быстро, так как скачает только эмулятор ядра Linux и утилиту для запуска подсистемы, которая окажется в системной папке в трех экземплярах: wsl.exe, bash.exe и ubuntu.exe (вместо ubuntu будет имя Вашего дистрибутива). Все они равнозначны и делают одно и то же — запускают собственный эмулятор терминала, в нем linux’овый bash работающий под эмулятором ядра. При первом же запуске нас попросят придумать логин и пароль для пользователя по умолчанию, а после произойдет непосредственно установка дистрибутива. В качестве пользователя по умолчанию указываем root без пароля — это потребуется для дальнейших шагов. Безопасность не пострадает, кроме того при подготовке материалов к статье, в англоязычном туториале, я наткнулся на информацию, что новые версии WSL теперь делают пользователем по умолчанию root без пароля без лишних вопросов.

Дожидаемся установки. Далее первым делом стоит обновить зеркала apt на ближайшие. Для этого понадобится CLI текстовый редактор. В комплекте только vi, я же больше предпочитаю nano, поэтому ставлю его:

apt install nano

sudo вводить не требуется, так как мы уже под root’ом. Отредактируем файл /etc/apt/sources.list:

nano /etc/apt/sources.list

У меня лучше всего работают зеркала Яндекса, поэтому мой файл выглядит так:

deb http://mirror.yandex.ru/ubuntu/ xenial main universe restricted
deb-src http://mirror.yandex.ru/ubuntu/ xenial main universe  restricted

deb http://mirror.yandex.ru/ubuntu/ xenial-security main universe restricted
deb-src http://mirror.yandex.ru/ubuntu/ xenial-security main universe restricted

deb http://mirror.yandex.ru/ubuntu/ xenial-updates main universe restricted
deb-src http://mirror.yandex.ru/ubuntu/ xenial-updates main universe restricted

Нажимаем Ctrl+O для сохранения и Ctrl+X для выхода. Теперь можно обновить систему до актуального состояния:

apt update && apt upgrade

После обновления можно создать нашего основного пользователя. В данной статье я назову его user1, Вы же можете задать привычное имя:

addgroup --gid 1000 user1
adduser --home /home/user1 --shell /bin/bash --uid 1000 -G user1,sudo user1

Далее переходим в папку юзера, зайдем под ним, установим пароль и отредактируем файл ~/.bashrc:

cd /home/user1
su user1
passwd
nano .bashrc

Мой базовый .bashrc выглядит так

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm|xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
    # We have color support; assume it's compliant with Ecma-48
    # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
    # a case would tend to support setf rather than setaf.)
    color_prompt=yes
    else
    color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    if [[ ${EUID} == 0 ]] ; then
        PS1='${debian_chroot:+($debian_chroot)}[33[01;31m]h[33[01;34m] W $[33[00m] '
    else
        PS1='${debian_chroot:+($debian_chroot)}[33[01;32m]u@h[33[00m] [33[01;34m]w $[33[00m] '
    fi
else
    PS1='${debian_chroot:+($debian_chroot)}u@h w $ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="[e]0;${debian_chroot:+($debian_chroot)}u@h wa]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '''s/^s*[0-9]+s*//;s/[;&|]s*alert$//''')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

Все, подсистема готова к использованию… почти…

Установка X-сервера, Xfce и прочих GUI’шных приложений

Первая же проблема, на которую я натолкнулся — bash-completion в предлагаемом эмуляторе терминала работал, мягко говоря, некорректно. Кроме того, данный эмулятор не умеет вкладки, а каждый его экземпляр запускает все в новом пространстве процессов, с отдельным init’ом (который кстати не заменить). Мне захотелось нормальный эмулятор терминала, некоторых других GUI приложений, а так же панельку, чтоб это все быстро запускать.

Когда я гуглил этот вопрос, я наткнулся на множество проблем, вроде необходимости перевода dbus на tcp протокол. На данный момент всех этих проблем нет. В подсистеме нормально работают unix-domain-socket’ы и все спокойно общается через них.

Первым делом нам понадобится X-сервер, притом установленный в основную систему (в Windows). Лично я использую для этих целей VcXsrv — порт X11 на Windows. Официальный сайт указанный в about самой утилиты его сейчас не предоставляет, поэтому гуглим установщик и устанавливаем все по умолчанию.

Пока идет установка возвращаемся в терминал WSL, командой exit выходим обратно в root’а. Первым делом настроим русские локали:

locale-gen ru_RU
locale-gen ru_RU.UTF-8
update-locale

Далее установим некоторые компоненты Xfce. Можно конечно установить его целиком из мета-пакета, но большинство компонентов нам не понадобится, а модульная архитектура Xfce позволяет нам поставить только необходимое:

apt install -y xfce4-session xfce4-notifyd xfce4-appfinder xfce4-panel xfce4-quicklauncher-plugin xfce4-whiskermenu-plugin xfce4-xkb-plugin xfce4-settings xfce4-terminal xfce4-taskmanager mousepad

Запускать каждый раз окружение руками не очень удобно, поэтому я автоматизировал данный процесс. Для этого в основной системе создадим в удобном для нас месте папку, а в ней 3 файла для запуска:

  1. config.xlaunch — файл настроек для VcXsrv
    <?xml version="1.0" encoding="UTF-8"?>
    <XLaunch
    WindowMode="MultiWindow"
    ClientMode="NoClient"
    LocalClient="False"
    Display="0"
    LocalProgram="xcalc"
    RemoteProgram="xterm"
    RemotePassword=""
    PrivateKey=""
    RemoteHost=""
    RemoteUser=""
    XDMCPHost=""
    XDMCPBroadcast="False"
    XDMCPIndirect="False"
    Clipboard="True"
    ClipboardPrimary="True"
    ExtraParams=""
    Wgl="True"
    DisableAC="False"
    XDMCPTerminate="False"
    />
  2. x-run.vbs — WSL всегда запускается со своим эмулятором терминала, если его закрыть — завершатся все его дочерние процессы. Чтоб данное окно не мозолило глаза, неплохо его запускать скрытым. К счастью в Windows встроен интерпретатор VBScript, который позволяет это сделать в одну строчку:

    WScript.CreateObject("Shell.Application").ShellExecute "wsl", "cd /home/user1; DISPLAY=:0 LANG=ru_RU.UTF-8 su user1 -c xfce4-session", "", "open", 0

    Поясню, что здесь происходит. Мы говорим VBscript выполнить приложение wsl с параметром cd /home/user1; DISPLAY=:0 LANG=ru_RU.UTF-8 su user1 -c xfce4-session, папка запуска нам не важна, поэтому пустая строка, действие open — запуск, 0 — скрытый режим. Самому wsl мы отдаем команду на выполнение: переход в папку пользователя, затем с установкой переменных окружения DISPLAY (дисплей X-сервера) и LANG (используемая локаль) мы запускаем xfce4-session от имени нашего пользователя user1 (благодаря команде su)

  3. start.bat — batch файл для запуска, по желанию его можно засунуть в автозагрузку
    start config.xlaunch
    wscript x-run.vbs

Далее можем запустить наш start.bat и настроить панель Xfce под себя. Замечу, что здесь я наткнулся на еще одну проблему — панель прекрасно отображается поверх всех окон, но вот выделить себе место, как панель на рабочем столе Windows она не может. Если кто знает решение данной проблемы, поделитесь в комментариях.

Ну и под конец данной части, скриншот моего рабочего стола:

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

Запускать Linux приложения напрямую из Windows можно через те же 3 команды — bash, wsl или ubuntu. Не забываем, что по умолчанию запуск идет от root, поэтому стоит понижать привилегии через su, так же нужно не забывать передавать переменную окружения DISPLAY=:0 если приложению требуется X-сервер. Так же нужно менять папку, из которой должно работать приложение, через cd внутри WSL. Пример, посчитаем md5 для file.txt на диске D средствами Linux’овой md5sum:

wsl md5sum < d:file.txt

Доступ к файловой системе Linux так же имеется, лежит она в %localappdata%PackagesCanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgscLocalStaterootfs. Читать таким образом файлы можно, а вот писать — не желательно, можно поломать файловую систему. Думаю проблема в том, что Windows не умеет работать с правами и владельцами файловой системы Linux.

Из Linux так же можно запускать Windows приложения. Просто запускаем exe-шник и он выполнится в основной системе.

Диски Windows монтируются в /mnt в соответствии со своими буквами в нижнем регистре. Например диск D будет смонтирован в /mnt/d. Из Linux можно свободно читать и писать файлы Windows. Можно делать на них симлинки. Права у таких файлов всегда будут 0777, а владельцем будет root.

Сетевой стек у подсистемы общий с Windows. Сервер поднятый в Linux будет доступен на localhost в Windows и наоборот. Однако unix-domain-socket для Windows будет просто пустым файлом, работать с этим можно только внутри Linux. Выход во внешнюю сеть у Linux так же есть, в том числе можно слушать порты, если этого не запрещает фаервол.
ifconfig в Linux и ipconfig в Windows выдают одинаковую информацию о сетевых интерфейсах.

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

Особенности, ограничения и подводные камни

Ядро Linux в WSL не настоящее. Это всего лишь прослойка-эмулятор, которая часть Linux-специфичных задач выполняет сама, а часть проксирует напрямую в ядро winNT. Большая часть api в нем реализована, но не все. Свое ядро собрать не получится, как и не получится подключить модули ядра (.ko, Kernel Object).

Init процесс у WSL тоже свой и заменить его, например, на system.d не выйдет. У меня давно есть желание написать менеджер демонов на go, который бы работал с файлами юнитов system.d и предоставлял бы схожий интерфейс, да все руки не доходят.

Нет поддержки openFUSE, соответственно примонтировать виртуальную или удаленную файловую систему не получится. Так же нельзя сделать mount из файла, mount вообще ничего кроме bind здесь, похоже, не умеет.

Так же нет никакой возможности разбить файловую систему Linux на несколько разделов/дисков.

Прямой доступ к железу практически отсутствует. Все таки мы находимся в песочнице Windows, а не в полноценном Linux. /dev и /sys заметно пустуют, в них лишь проц да виртуальные устройства. Доступ к GPU — только через X-сервер, напрямую — никак, так что нейросети обучать придется в Windows.

В JS разработке столкнулся с тем, что electron.js отказался запускаться в WSL, пришлось дублировать окружение node.js в Windows.

Итоги

Статья получилась довольно длинной, надеюсь, что она окажется еще и полезной.
WSL для меня лично оказался инструментом вполне юзабельным, решающим мои задачи fullstack backend разработчика. Виртуалка с Linux за полгода так и не понадобилась. По общим ощущениям Windows+WSL намного функциональнее, чем Linux+Wine.

Пока писал статью, обнаружил, что в Microsoft Store появилась сборка WSL с Debian 9.3, данный дистрибутив мне более симпатичен, чем Ubuntu, поэтому буду пробовать ставить.

Cover image for Windows Subsystem for Linux (WSL)

KenjiGoh

KenjiGoh

Posted on Nov 19, 2021

• Updated on Dec 26, 2021

Writing here for sharing and also for my personal reference as I have very poor memory and tend to forget some commands.

For windows users, you can download WSL (Windows Subsystem for Linux) on powershell. WSL lets developers run a Linux environment directly on windows Read more here

After installing, in Command Prompt or PowerShell, type wsl and it will open the WSL terminal window:

wsl

Enter fullscreen mode

Exit fullscreen mode

To open a VS Code, type code . from the ubuntu terminal.

code .

Enter fullscreen mode

Exit fullscreen mode

Go back to root directory

cd /

Enter fullscreen mode

Exit fullscreen mode

Mounting

/mnt is a standard subdirectory of the root directory on Linux. The /mnt/c/ directory basically means mounting on Windows C drive. Therefore if u see this path, it means u are accessing a folder that resides in Windows. Read more here

/mnt/c/<file_path>

Enter fullscreen mode

Exit fullscreen mode

Windows-WSL

sudo means «super user do» — a Linux command that allows you to executedddd programs as a super user (aka root user)

sudo

Enter fullscreen mode

Exit fullscreen mode

Before we go into installing new packages, lets cover some of the essential commands to help with troubleshooting.
Key terminologies to know:

  1. postgres is one of the default PostgreSQL database
  2. postgres is also the default admin user in PostgreSQL
  3. psql — interactive commandline tool

Basic Commands to Know

To check status of database:

sudo service postgresql status

Enter fullscreen mode

Exit fullscreen mode

To start running your database

sudo service postgresql start

Enter fullscreen mode

Exit fullscreen mode

To stop running your database

sudo service postgresql stop

Enter fullscreen mode

Exit fullscreen mode

Installation of Packages

To update & upgrade our Ubuntu to latest packages:

sudo apt-get update && sudo apt-get upgrade

Enter fullscreen mode

Exit fullscreen mode

To install package such as node, python or postgresql

sudo apt-get install <package>

Enter fullscreen mode

Exit fullscreen mode

To check version, e.g. postgreSQL, you type either one of this.

psql -V
psql --version

Enter fullscreen mode

Exit fullscreen mode

To see all the command documentations, you can either type one of the following commands:

-?
--help
man postgres

Enter fullscreen mode

Exit fullscreen mode

Show information about all PostgreSQL clusters

 pg_lsclusters

Enter fullscreen mode

Exit fullscreen mode

Default Databases of Postgres

Most Postgres servers have three databases defined by default: template0, template1 and postgres. (yes it is a little confusing for first-timer, default user is postgres and one of the default database name is also postgres)

The default admin user, postgres, needs a password assigned in order to connect to a database. By default, the postgres user has no password and can hence only connect if ran by the postgres system user. Therefore, we have to set a password for the postgres user:

sudo passwd postgres

Enter fullscreen mode

Exit fullscreen mode

You will see the command line change to postgres=#

To exit the postgres=#, enter q or Ctrl+D:

q

Enter fullscreen mode

Exit fullscreen mode

To switch from root user to the default admin user, postgres.

su - postgres

Enter fullscreen mode

Exit fullscreen mode

You will see something like this. You can now run commands as the PostgreSQL superuser.

postgres@DESKTOP-ORMQU9O:~$

Enter fullscreen mode

Exit fullscreen mode

To create a new user:

createuser --interactive --pwprompt

Enter fullscreen mode

Exit fullscreen mode

You will be prompt the following:

postgres@DESKTOP-ORMQU9O:~$ createuser --interactive --pwprompt
Enter name of role to add: kenji
Enter password for new role: 
Enter it again: 
Shall the new role be a superuser? (y/n) 

Enter fullscreen mode

Exit fullscreen mode

I (postgres user in this case) have created a new user called kenji.

To create a new database called simple_blog:

createdb simple_blog

Enter fullscreen mode

Exit fullscreen mode

To destroy a database:

dropdb simple_blog

Enter fullscreen mode

Exit fullscreen mode

Using psql Interactive Shell as default postgres user

To run Postgres with psql interactive shell (you can also just type psql), it will prompt you for a password:

sudo -u postgres psql

Enter fullscreen mode

Exit fullscreen mode

You will be greeted with the following:

psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.

postgres=#

Enter fullscreen mode

Exit fullscreen mode

Press Ctrl+D to exit and we will return to this:

postgres@DESKTOP-ORMQU9O:~$

Enter fullscreen mode

Exit fullscreen mode

Here we can switch to the new user we have just created:

postgres@DESKTOP-ORMQU9O:~$ su - kenji

Enter fullscreen mode

Exit fullscreen mode

And you will then see this instead (after password prompt):

kenji@DESKTOP-ORMQU9O:~$ 

Enter fullscreen mode

Exit fullscreen mode

We can enter the psql command line by typing:

kenji@DESKTOP-ORMQU9O:~$ psql

Enter fullscreen mode

Exit fullscreen mode

And you will see this:

psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.

kenji=#

Enter fullscreen mode

Exit fullscreen mode

psql is an interactive terminal program that allows you to interactively enter, edit and execute SQL commands. Remember to put ‘;’ to end the SQL statement.

With psql shell open, to see what user accounts have been created:

kenji=# du

Enter fullscreen mode

Exit fullscreen mode

To see all other available backslash commands:

kenji=# ?

Enter fullscreen mode

Exit fullscreen mode

To exit the help log, type ‘q’ and press Enter:

kenji=# q

Enter fullscreen mode

Exit fullscreen mode

We can also check connection info to see port which database, which user and which port you are connected to:

kenji=# conninfo

Enter fullscreen mode

Exit fullscreen mode

You will see this:

You are connected to database "kenji" as user "kenji" via socket in "/var/run/postgresql" at port "5432".

Enter fullscreen mode

Exit fullscreen mode

Start psql to specific database you have created

When not in psql shell, You can also startup psql to a specific database with the below commaned:

psql simple_blog

Enter fullscreen mode

Exit fullscreen mode

You will be greeted with the following:

psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.

simple_blog=#

Enter fullscreen mode

Exit fullscreen mode

To see all database:

l

Enter fullscreen mode

Exit fullscreen mode

You can write SQL statement directly, remember to end with semi-colon:

simple_blog=# CREATE TABLE my_table (
simple_blog(# first integer not null default 0,
simple_blog(# second text)
simple_blog-# ;
CREATE TABLE

Enter fullscreen mode

Exit fullscreen mode

Now if you type ‘d my_table’, you will see the created table

simple_blog=# d my_table
              Table "public.my_table"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 first  | integer |           | not null | 0
 second | text    |           |          | 

Enter fullscreen mode

Exit fullscreen mode

As always, to learn more, it is best to read the documentation, as some solutions shared by others might be outdated.

How to Install Windows Subsystem for Linux (WSL2) on Windows 10?

Windows Subsystem for Linux (WSL) is an awesome feature of Windows 10. No more VMware or Oracle VirtualBox is required to run Linux on Windows. WSL is faster and less resource consuming, zero or less configuration compared to any other traditional Virtual Machines (VM). Installation and setup of Linux Distribution is lightning-fast. Because of seamless integration between Windows Host OS and Linux Guest OS, no separate SSH client (e.g. Putty) or SCP client (e.g. WinSCP) is required.  Docker can run directly inside of WSL2 (a full Linux Kernel built by Microsoft). Easy to setup isolated AWS cloud development environment locally using Docker, LocalStack, AWS CLI, SAM CLI, VSCode etc. What else do we, developers need!

Prerequisite

For WSL2, Windows 10 has to be on

  • Version 1903 or higher with Build 18362 or higher for x64 systems.
  • Version 2004 or higher with Build 19041 or higher for ARM64 systems.

In case, if you are wondering how to verify this,
Open Windows Run command (Windows logo key + R), type winver and click «OK» button».

turn windows10 optional feature on

or, open Windows command prompt and type ver

c:>ver
Microsoft Windows [Version 10.0.18363.1679]

Enable Windows Optional Feature

Next, we’ll turn on following two windows feature

  • Windows Subsystem for Linux
  • Virtual Machine Platform

We can do it in two ways:
Option#1:

  1. Open Windows Run command (Windows logo key + R)
  2. Type optionalfeatures
  3. Click «OK» button».
  4. Select checkboxes for Windows Subsystem for Linux and Virtual Machine Platform features.

    turn windows10 optional feature on

  5. Click «OK» button to apply changes.
  6. Once done, «Windows needs to reboot your PC to finish installing the requested changes«. So, click «Restart now» button.

Option#2:

  1. Open Windows PowerShell in «Run as Administrator«.
  2. Execute following command
PS C:> Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux, VirtualMachinePlatform

Do you want to restart the computer to complete this operation now?
[Y] Yes  [N] No  [?] Help (default is "Y"): Y             
  1. To apply this change, you need to restart the system. Therefore, enter «Y» when you will be asked to restart.

Reference: Enable-WindowsOptionalFeature

Enable-WindowsOptionalFeature
      -FeatureName <String[]>
      [-PackageName <String>]
      [-All]
      [-LimitAccess]
      [-Source <String[]>]
      [-NoRestart]
      [-Online]
      [-WindowsDirectory <String>]
      [-SystemDrive <String>]
      [-LogPath <String>]
      [-ScratchDirectory <String>]
      [-LogLevel <LogLevel>]
      [<CommonParameters>]

Description:

The Enable-WindowsOptionalFeature cmdlet enables or restores an optional feature in a Windows image.

Use the Online parameter to specify the running operating system on your local computer, or use the Path parameter to specify the location of a mounted Windows image.

The FeatureName parameter specifies the feature to add. You can specify more than one feature in the same package. Separate feature names with a comma.

Notes:
Get-WindowsOptionalFeature cmdlet gives all the features availble in the running operating system.

PS C:> Get-WindowsOptionalFeature -Online

FeatureName : Printing-PrintToPDFServices-Features
State       : Enabled

FeatureName : Printing-XPSServices-Features
State       : Enabled

FeatureName : TelnetClient
State       : Disabled

FeatureName : TFTP
State       : Disabled

FeatureName : LegacyComponents
State       : Disabled

FeatureName : DirectPlay
State       : Disabled

FeatureName : Printing-Foundation-Features
State       : Enabled

FeatureName : Printing-Foundation-InternetPrinting-Client
State       : Enabled

FeatureName : Printing-Foundation-LPDPrintService
State       : Disabled

FeatureName : Printing-Foundation-LPRPortMonitor
State       : Disabled

FeatureName : SimpleTCP
State       : Disabled

FeatureName : Windows-Identity-Foundation
State       : Disabled

FeatureName : NetFx3
State       : DisabledWithPayloadRemoved

FeatureName : WCF-HTTP-Activation
State       : Disabled

FeatureName : WCF-NonHTTP-Activation
State       : Disabled

FeatureName : IIS-WebServerRole
State       : Disabled

FeatureName : IIS-WebServer
State       : Disabled

FeatureName : IIS-CommonHttpFeatures
State       : Disabled

FeatureName : IIS-HttpErrors
State       : Disabled

FeatureName : IIS-HttpRedirect
State       : Disabled

FeatureName : IIS-ApplicationDevelopment
State       : Disabled

FeatureName : IIS-Security
State       : Disabled

FeatureName : IIS-RequestFiltering
State       : Disabled

FeatureName : IIS-NetFxExtensibility
State       : Disabled

FeatureName : IIS-NetFxExtensibility45
State       : Disabled

FeatureName : IIS-HealthAndDiagnostics
State       : Disabled

FeatureName : IIS-HttpLogging
State       : Disabled

FeatureName : IIS-LoggingLibraries
State       : Disabled

FeatureName : IIS-RequestMonitor
State       : Disabled

FeatureName : IIS-HttpTracing
State       : Disabled

FeatureName : IIS-URLAuthorization
State       : Disabled

FeatureName : IIS-IPSecurity
State       : Disabled

FeatureName : IIS-Performance
State       : Disabled

FeatureName : IIS-HttpCompressionDynamic
State       : Disabled

FeatureName : IIS-WebServerManagementTools
State       : Disabled

FeatureName : IIS-ManagementScriptingTools
State       : Disabled

FeatureName : IIS-IIS6ManagementCompatibility
State       : Disabled

FeatureName : IIS-Metabase
State       : Disabled

FeatureName : WAS-WindowsActivationService
State       : Disabled

FeatureName : WAS-ProcessModel
State       : Disabled

FeatureName : WAS-NetFxEnvironment
State       : Disabled

FeatureName : WAS-ConfigurationAPI
State       : Disabled

FeatureName : IIS-HostableWebCore
State       : Disabled

FeatureName : WCF-Services45
State       : Enabled

FeatureName : WCF-HTTP-Activation45
State       : Disabled

FeatureName : WCF-TCP-Activation45
State       : Disabled

FeatureName : WCF-Pipe-Activation45
State       : Disabled

FeatureName : WCF-MSMQ-Activation45
State       : Disabled

FeatureName : WCF-TCP-PortSharing45
State       : Enabled

FeatureName : IIS-StaticContent
State       : Disabled

FeatureName : IIS-DefaultDocument
State       : Disabled

FeatureName : IIS-DirectoryBrowsing
State       : Disabled

FeatureName : IIS-WebDAV
State       : Disabled

FeatureName : IIS-WebSockets
State       : Disabled

FeatureName : IIS-ApplicationInit
State       : Disabled

FeatureName : IIS-ASPNET
State       : Disabled

FeatureName : IIS-ASPNET45
State       : Disabled

FeatureName : IIS-ASP
State       : Disabled

FeatureName : IIS-CGI
State       : Disabled

FeatureName : IIS-ISAPIExtensions
State       : Disabled

FeatureName : IIS-ISAPIFilter
State       : Disabled

FeatureName : IIS-ServerSideIncludes
State       : Disabled

FeatureName : IIS-CustomLogging
State       : Disabled

FeatureName : IIS-BasicAuthentication
State       : Disabled

FeatureName : IIS-HttpCompressionStatic
State       : Disabled

FeatureName : IIS-ManagementConsole
State       : Disabled

FeatureName : IIS-ManagementService
State       : Disabled

FeatureName : IIS-WMICompatibility
State       : Disabled

FeatureName : IIS-LegacyScripts
State       : Disabled

FeatureName : IIS-LegacySnapIn
State       : Disabled

FeatureName : IIS-FTPServer
State       : Disabled

FeatureName : IIS-FTPSvc
State       : Disabled

FeatureName : IIS-FTPExtensibility
State       : Disabled

FeatureName : MSMQ-Container
State       : Disabled

FeatureName : MSMQ-DCOMProxy
State       : Disabled

FeatureName : MSMQ-Server
State       : Disabled

FeatureName : MSMQ-ADIntegration
State       : Disabled

FeatureName : MSMQ-HTTP
State       : Disabled

FeatureName : MSMQ-Multicast
State       : Disabled

FeatureName : MSMQ-Triggers
State       : Disabled

FeatureName : IIS-CertProvider
State       : Disabled

FeatureName : IIS-WindowsAuthentication
State       : Disabled

FeatureName : IIS-DigestAuthentication
State       : Disabled

FeatureName : IIS-ClientCertificateMappingAuthentication
State       : Disabled

FeatureName : IIS-IISCertificateMappingAuthentication
State       : Disabled

FeatureName : IIS-ODBCLogging
State       : Disabled

FeatureName : MediaPlayback
State       : Enabled

FeatureName : WindowsMediaPlayer
State       : Enabled

FeatureName : DataCenterBridging
State       : Disabled

FeatureName : SmbDirect
State       : Enabled

FeatureName : HostGuardian
State       : Disabled

FeatureName : SMB1Protocol-Deprecation
State       : Disabled

FeatureName : MSRDC-Infrastructure
State       : Enabled

FeatureName : TIFFIFilter
State       : Disabled

FeatureName : NetFx4-AdvSrvs
State       : Enabled

FeatureName : NetFx4Extended-ASPNET45
State       : Disabled

FeatureName : MultiPoint-Connector
State       : Disabled

FeatureName : MultiPoint-Connector-Services
State       : Disabled

FeatureName : MultiPoint-Tools
State       : Disabled

FeatureName : Windows-Defender-Default-Definitions
State       : Disabled

FeatureName : SearchEngine-Client-Package
State       : Enabled

FeatureName : MicrosoftWindowsPowerShellV2Root
State       : Enabled

FeatureName : MicrosoftWindowsPowerShellV2
State       : Enabled

FeatureName : Client-DeviceLockdown
State       : Disabled

FeatureName : Client-EmbeddedShellLauncher
State       : Disabled

FeatureName : Client-EmbeddedBootExp
State       : Disabled

FeatureName : Client-EmbeddedLogon
State       : Disabled

FeatureName : Client-KeyboardFilter
State       : Disabled

FeatureName : Client-UnifiedWriteFilter
State       : Disabled

FeatureName : AppServerClient
State       : Disabled

FeatureName : WorkFolders-Client
State       : Enabled

FeatureName : Client-ProjFS
State       : Disabled

FeatureName : SMB1Protocol
State       : Disabled

FeatureName : SMB1Protocol-Client
State       : Disabled

FeatureName : SMB1Protocol-Server
State       : Disabled

FeatureName : Internet-Explorer-Optional-amd64
State       : Enabled

FeatureName : Microsoft-Windows-Subsystem-Linux
State       : Disabled

FeatureName : HypervisorPlatform
State       : Disabled

FeatureName : VirtualMachinePlatform
State       : Disabled

FeatureName : Containers-DisposableClientVM
State       : Enabled

FeatureName : Microsoft-Hyper-V-All
State       : Disabled

FeatureName : Microsoft-Hyper-V
State       : Disabled

FeatureName : Microsoft-Hyper-V-Tools-All
State       : Disabled

FeatureName : Microsoft-Hyper-V-Management-PowerShell
State       : Disabled

FeatureName : Microsoft-Hyper-V-Hypervisor
State       : Disabled

FeatureName : Microsoft-Hyper-V-Services
State       : Disabled

FeatureName : Microsoft-Hyper-V-Management-Clients
State       : Disabled

FeatureName : DirectoryServices-ADAM-Client
State       : Disabled

FeatureName : Windows-Defender-ApplicationGuard
State       : Disabled

FeatureName : ServicesForNFS-ClientOnly
State       : Disabled

FeatureName : ClientForNFS-Infrastructure
State       : Disabled

FeatureName : NFS-Administration
State       : Disabled

FeatureName : Containers
State       : Disabled

Download and Install Linux Kernel update package

Based on your System type download corresponding Linux Kernel update package.

  • WSL2 Linux Kernel update package for x64-based PC
  • WSL2 Linux Kernel update package for ARM64-based PC

Installation Steps:

  1. Double click to run the downloaded Windows Installer Package.
  2. In User Access Control Wizard, click «Yes» when it will ask «Do you want to allow this app to make changes to your device?«
  3. Click «Finish» button to complete.

turn windows10 optional feature on

Set WSL default version to 2 (WSL2)

Run the below command in Windows Command Prompt or Windows PowerShell to change the default installation version for new Linux distribution.

C:UsersAbhijit>wsl  --set-default-version 2
For information on key differences with WSL 2 please visit https://aka.ms/wsl2
The operation completed successfully.

Install Linux Distribution

Finally, we are good to install the preferred Linux distribution. We can do it in multiple ways.

Option#1:

  1. Run the following command in Windows Command Prompt or Windows PowerShell to display a list of available distributions for installation with wsl --install
    C:UsersAbhijit>wsl --list --online
    The following is a list of valid distributions that can be installed.
    Install using 'wsl --install -d <Distro>'.
    
    NAME            FRIENDLY NAME
    Ubuntu          Ubuntu
    Debian          Debian GNU/Linux
    kali-linux      Kali Linux Rolling
    openSUSE-42     openSUSE Leap 42
    SLES-12         SUSE Linux Enterprise Server v12
    Ubuntu-16.04    Ubuntu 16.04 LTS
    Ubuntu-18.04    Ubuntu 18.04 LTS
    Ubuntu-20.04    Ubuntu 20.04 LTS
    
  2. Now, pass the desired distribution name while running wsl --install
    C:UsersAbhimun>wsl --install --distribution Ubuntu-20.04
    Downloading: Ubuntu 20.04 LTS
    Installing: Ubuntu 20.04 LTS
    Ubuntu 20.04 LTS has been installed.
    Launching Ubuntu 20.04 LTS...
    
  3. Once installed, it will be Launched automatically.

Option#2:

  1. Open Microsoft Store
  2. Choose your preferred Linux Distributions (e.g. Ubuntu).
  3. Click «Install» button to start.

    turn windows10 optional feature on

Option#3:

  1. In case if Microsoft Store app is retricted by your organization or not avilable, then you can download offline installer.

Downloading distributions:

  • Ubuntu 20.04
  • Ubuntu 20.04 ARM
  • Ubuntu 18.04
  • Ubuntu 18.04 ARM
  • Ubuntu 16.04
  • Debian GNU/Linux
  • Kali Linux
  • SUSE Linux Enterprise Server 12
  • SUSE Linux Enterprise Server 15 SP2
  • openSUSE Leap 15.2
  • Fedora Remix for WSL

This will cause the .appx packages to download to a folder of your choosing.

  1. Double click the downloaded package.
  2. Click «Install» to start.

    turn windows10 optional feature on

Launch Linux Distribution

At the end of installation, you will get option to Launch the installed Linux Distribution. In my case, it is Ubuntu 20.04 and I am seeing the following in my screen.

Installing, this may take a few minutes...
Please create a default UNIX user account. The username does not need to match your Windows username.
For more information visit: https://aka.ms/wslusers
Enter new UNIX username: abhijit
New password:
Retype new password:
passwd: password updated successfully
Installation successful!
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.10.16.3-microsoft-standard-WSL2 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Thu Aug 26 01:36:36 EDT 2021

  System load:  0.0                Processes:             8
  Usage of /:   0.4% of 250.98GB   Users logged in:       0
  Memory usage: 1%                 IPv4 address for eth0: 172.23.22.192
  Swap usage:   0%

0 updates can be installed immediately.
0 of these updates are security updates.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update


This message is shown once once a day. To disable it please create the
/home/abhijit/.hushlogin file.
[email protected]:~$

Bonus Section

If you’re wondering how to change the hostname permanently on Ubuntu running on WSL2, then following video will help you.

If you prefer reading, then check the following article on How to change hostname on Ubuntu running on Windows WSL?

Summary

Because of «..seamless integration between Windows and Linux, fast boot times, a small resource footprint, and requires no VM configuration or management«, lightning-fast installation & setup of Linux distribution, WSL2 is becoming the popular choice for local development.

References

  • Comparing WSL 1 and WSL 2
  • Offline Linux Distributions
  • Deployment Image Servicing and Management (DISM) platform


, Windows Subsystem for Linux
, WSL2
, VMware
, Oracle VM
, VirtualBox
, Virtual Machine
, Docker
, Putty
, WinSCP
, Linux Kernel
, Windows 10
, Ubuntu on Windows 10
, WSL
, Virtual Machine Platform
, Windows Feature
, winver
, 2-step Verification
, optionalfeatures
, Easy Development
, Build 18362
, Version 1903
, x64
, ARM64
, PowerShell
, Ubuntu
, Kali
, Debian
, OpenSUSE
, Alpine WSL
, wsl —install
, classic

The Windows Subsystem for Linux or Windows WSL is a great solution for developers to natively work within Linux right on their Windows 10 version desktop.

If you’ve spent way too much time partitioning hard drives to have several Linux systems installed with Windows, you’re in luck with this article.

The fairy code-mother at Microsoft has decided to give you another option: The Windows Subsystem for Linux (WSL). WSL makes running a Linux system alongside Windows so much easier, and more flexible.

In this tutorial, you’ll learn how to get started with WSL. You’ll learn how to get started to learning how to use some nifty tools making WSL even more versatile than using bash or PowerShell on their own.

What is WSL?

WSL or C:WindowsSystem32wsl.exe is a Windows tool that allows you to install a Linux distribution as an app from the Windows store.

Since WSL is a simple Windows executable, you can call it from a command prompt or PowerShell terminal. We’ll go deeper into that topic later. For now, it’s important to understand a little more about what WSL is doing under the hood.

wsl.exe
wsl.exe

How to Enable WSL

To set up and enable WSL involves installing a Linux distribution alongside Windows 10. But in a way that allows the two different operating systems to interact with each other.

Prerequisites

If you’re an IT pro struggling with too many password reset requests in Active Directory, check out Specops uReset, a secure SSPR solution.

To install WSL on Windows, you have one requirement to meet; you must have a Windows 10 64-bit computer Build 18917 or later.

You can find your Windows 10 build by running the winver utility.

Windows build 1809

Enabling the WSL Windows Feature

WSL is a cinch to enable; no download required. It’s simply a single Windows feature.

To enable WSL, open up PowerShell as administrator and run the following:

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

Related: How to Run PowerShell as Administrator

Once complete, restart your computer and you’re done!

Downloading a Linux Distribution for WSL

WSL does not install any Linux distribution on its own. You’ll need to install one. Once Windows 10 comes back up, start setting up your chosen Linux distribution.

First, open up the Microsoft Store and search for ‘WSL’. You should soon see a list of Linux distributions show up.

Next, choose your distribution of choice and install it. This tutorial will be using Ubuntu 18.04. At the time of this writing, you have a few other distributions available as well such as:

  • Ubuntu 16.04 LTS
  • Ubuntu 18.04 LTS
  • OpenSUSE Leap 15
  • OpenSUSE Leap 42
  • SUSE Linux Enterprise Server 12
  • SUSE Linux Enterprise Server 15
  • Kali Linux
  • Debian GNU/Linux
  • Fedora Remix for WSL
  • Pengwin
  • Alpine WSL

Setting your WSL Version

You might have to enable Linux to work with WSL version 2. If so, you can do so by following the below instructions.

In a PowerShell console:

  1. List which versions of Linux you have installed by running wsl -l or wsl --list.
  2. Once you have the list, copy the name of the distro you want to run with WSL2 and run wsl --set-version <Distro> 2, replacing <Distro> with the name you copied earlier.
  3. Confirm the command was successful by running wsl -l -v or wsl --list --verbose. This command will return a full list of WSL distros and the version each distro is using.
Setting WSL Linux distro
Setting WSL Linux distro

You can also set your default WSL version for any distros you install in the future to WSL2 by running wsl --set-default-version 2

Starting up WSL

To start using WSL, open up a PowerShell terminal and type wsl. If you’ve set up WSL correctly, you’ll enter a bash terminal running on the WSL distro of choice. From here, you can run any Linux commands you wish.

Below you will find a reference to all of the options the wsl.exe provides when starting up.

Command Explanation Example
exec, -e Will run command using without using default shell wsl -e curl google.com
Passes anything after this parameter to default shell. Leaving the operator out will also work. wsl — curl google.com, wsl curl google.com
distribution, -d Opens a terminal in the specified distribution’s shell wsl -d Ubuntu-18.04
user, -u Runs WSL command as the specified user as long as user exists on that distro wsl -d Ubuntu-18.04 -u tux_user
export Exports the specified distribution to a tar file on your local system. wsl –export Ubuntu ./Test-Ubuntu.tar
import [–version] Imports a tar file as a new WSL distribution. Can specify WSL version with the –version option wsl –import Test-Ubuntu C:dataTest-Ubuntu .Test-Ubuntu.tar
list, -l [Options] wsl –list
all List all installed WSL distributions wsl -l –all
running List only WSL distributions that are currently running wsl -l –running
quiet, -q Only show WSL distribution names wsl -l -q
verbose, -v Show detailed information about all WSL distributions wsl -l -v
set-default, -s Sets the specified WSL distribution as the default distribution for WSL commands. wsl -s Test-Ubuntu
set-default-version Changes the default WSL version for all new distributions installed to that system wsl –set-default-version 2
set-version Changes the WSL version of the specified distribution wsl –set-version Test-Ubuntu 2
shutdown Immediately terminates all running WSL distributions wsl –shutdown
terminate, -t Terminates the specified WSL distribution wsl -t Test-Ubuntu
unregister Unregisters the specified WSL distribution wsl –unregister Test-Ubuntu
help Display information about using WSL wsl –help

Once you get comfortable using these switches, you’ll find that running and managing applications through WSL is much easier than managing Linux virtual machines on your own.

Quick tip: Discover all flags and arguments for to WSL by running wsl --help.

When you’re finished, type exit to go back back to the PowerShell terminal.

Sharing Windows/Linux Resources via WSL

One of the best parts of WSL is that it can seamlessly share Windows and Linux resources with each other. At this time, you can share file systems, environment variables, network resources, and command-line tools like cmd and PowerShell.

All examples you will see in this section are via the WSL Ubuntu Linux distro. Your mileage may vary if you’ve chosen to download a different distro.

Sharing File Systems

The file system is one of the most useful things to share with WSL. WSL allows you to work with both file systems as if they were one.

The Windows 10 file system is mounted as a directory in Linux while your Linux file system will be mounted as a folder in Windows.

Finding the Linux File System from Windows with Environment Variables

When you install a Linux distro with WSL, it will sometimes add a Windows environment variable. In the case of the WSL Ubuntu Linux distro, it will create an environment variable called UBUNTU_HOME. This environment variable points to the Linux /home/ubuntu directory from both Windows and WSL Ubuntu.

The path defined in UBUNTU_HOME can be used to run scripts that use resources across them, or set a default location for the Windows terminal (covered later).

Inspecting the WSL UBUNTU_HOME environment variable
Inspecting the WSL UBUNTU_HOME environment variable

Other distros may define a similar environment variable. Inspect the Windows environment variables with the PowerShell command Get-ChildItem -Path $Env: after installing a new Linux distro to see if any may have been added.

This environment variable shortcut is handy if you want to put everything in the /home/ubuntu directory. But let’s dig a little deeper into how it got there and how else you can reach it.

Finding the Linux File System from Windows via the Microsoft Store Packages Folder

Not every WSL distro is guaranteed to come with an easy way to reference it. It’s important that you learn how to find the Linux file system an alternative way.

Since most WSL Linux distributions will be installed from the Microsoft store, you can look for the Linux file system in the same place as other Windows store apps. Navigate to %USERPROFILE%AppDataLocalPackages to find the directory where your Windows store apps go. Then assume control of the folder as this is usually protected by default.

You will see many subfolders in the packages folder where your Linux distrubution file system may be presented. The WSL Ubuntu distro, for example, was under the CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc folder for me.

If you navigate into the package folder, you will find the Linux file system. For WSL Ubuntu, it’s located in the LocalStaterootfs folder. This is the root directory of your Linux distro.

Linux filesystem under %USERPROFILE%/AppData/Local/Packages/
Linux filesystem under %USERPROFILE%/AppData/Local/Packages/

Finding the Windows File System from Linux

To find the Windows 10 file system from Linux, open up WSL in Windows. WSL will then bring up a bash terminal. This bash terminal will start in your UBUNTU_HOME directory by default.

You can also find the root of your Windows storage volumes as well. Each of your Windows letter drives (C, D, E, etc) is treated as a mounted drive from the WSL Linux file system. You’ll find each volume mounted as /mnt/c, /mnt/d, etc as long as you have root privileges.

Bash equivalent of running Get-ChildItem C:WindowsSystem32 | Select-Object -First 5 running on WSL
Bash equivalent of running Get-ChildItem C:WindowsSystem32 | Select-Object -First 5 running on WSL

The WSL2 Filesystem

Navigating the WSL filesystem is fairly straightforward. Anyone not familiar with a Linux file system structure will appreciate being able to navigate it with the Windows Explorer. Bu if you want to switch to WSL2, it’s going to be a little more complicated.

WSL2 changes how everything works under the hood for sharing file systems. For starters, the filesystem is now a virtual hard disk in vhdx format instead of a directory.

You can find the vhdx file under %USERPROFILE%AppDataLocalPackagesCanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgscLocalState for an WSL Ubuntu distro.

You’ll find that VHDX files can be mounted in Windows with the Disk Manager tool. But, the virtual disks cannot be mounted while the WSL distro is registered.

Sharing Environment Variables

Environment variables are a crucial part of any operating system, making it easy to reference binaries and executables anywhere in your applications.

Before Windows 10 build 17063, the only environment variable shared between Windows 10 and WSL Linux was the PATH variable. Since then it is possible to share environment variables by using WSLENV the environment variable.

Using the WSLENV environment variable to share other environment variables can feel a little meta. To share environment variables across platforms, you actually have to set environment variables inside of another environment variable.

Overview

Sharing environment variables is a three-step process below. The only major difference when sharing across Windows/Linux is the switch argument used (full reference below).

  1. Define environment variable in Windows or Linux.
  2. Set the WSLENV environment variable equal to the previously defined environment variable followed by a switch argument (for path translation).
  3. Read the environment variable in Windows or Linux.

Sharing Options

You can make variables available four different ways depending on which platform you’d like the environment variable to show up on using switches (table shown below).

  • Windows filesystem to only be available from itself
  • WSL filesystem to only be available from WSL
  • WSL filesystem to be available on both WSL Linux and Windows
  • Windows filesystem to be be available on both WSL Linux and Windows
Flag Explanation
/p Single path. A variable set with this will be translated between the Windows and WSL Linux and made available to both.
/l List of paths. Similar to /p, except it can accept more than one path. On Windows, this list will be delimited by semicolons while on WSL Linux it will be delimited by colons.
/u Unix path. A path set with this flag can only be accessed when invoking WSL Linux from Windows. Can be used with either the /p or /l flags
/w Windows path. A path set with this flag can only be accessed when invoking Windows from WSL Linux. Can be used with either the /p or /l flags

Path Translation

The main reason to share environment variables is for path translation. As you may already know, Windows has user profile folders as Linux has user profile directories, for example. Each user has a predetermined “home folder” like C:Users<username> on Windows and /home/<username> on Linux.

Using the /p and /l switches, the WSL will translate these folder paths between platforms.

Sharing and Translating Windows Paths with Linux

You can share a single path or multiple paths at once using the /p and /l switches.

At a Windows command prompt and with a Windows environment variable defined called DESKTOP, assign a value of DESKTOP/p to the WSLENV variable. This allows you to access it from WSL Linux. You can see an example below.

Setting variables in Windows and accessing in Linux
Setting variables in Windows and accessing in Linux

The exact same procedure can be performed for multiple paths at once using the /l switch.

Sharing and Translating Linux Paths with Windows

To share and translate Linux path with Windows is the same procedure as it Windows although using Linux-specific commands to set environment variables.

For a deeper look at sharing environment variables, check out, this Microsoft article.

Sharing Network Resources

The networking component is another handy resource to share between Windows and WSL Linux.

Physical vs. Virtualized Network Interfaces

In WSL2, the network interfaces are virtualized. Virtualized network interfaces mean that WSL2 network instances can hold different IP configurations than their Windows 10 counterparts.

At the time of this writing, IP addresses for WSL2 Linux use Network Address Translation (NAT) to access network resources on Windows, though Microsoft has mentioned removing NAT is high on their backlog of issues to fix.

Same comparison from earlier, but against a WSL2 distro
Same comparison from earlier, but against a WSL2 distro

Client DNS Resolution

WSL will still both generate /etc/resolv.conf and /etc/hosts files to allow for DNS resolution. As long as you don’t explicitly override that behavior in /etc/wsl.conf, client DNS resolution will continue to work as expected.

You’ll learn more about the wsl.conf file later in the post.

Using PowerShell and Bash Together

One of the coolest features of WSL is the ability to seamlessly pass information to and from PowerShell and Bash on WSL.

PowerShell –> Bash

Since the WSL executable accepts input from the pipeline, you can call the wsl.exe command inside of PowerShell and accept stdin. This allows you to use WSL to pass entire objects from PowerShell into the WSL which then get processed with the bash terminal. You can see an example below.

Passing PowerShell to grep
Passing PowerShell to grep

Bash –> PowerShell/Cmd

You can also pass information from bash in the WSL to PowerShell and cmd just as easily. Below you can see an example of executing the Linux ls command and passing the output to the PowerShell Select-Object cmdlet via the pipeline.

Passing Bash output to PowerShell
Passing Bash output to PowerShell

You can also call some Windows cmd utilities from the WSL and pass the output back to Linux as long as both commands are in the system path.

Remember that the WSL knows what the system path is on both sides because it has access to the Windows PATH variable by default

Below you can see that you can run ipconfig, which is a Windows command, from within the WSL and pass that output to the Linux grep command. You can also see the opposite of calling the Linux command which and passing output to the Windows ipconfig command.

Executing a Windows command in Linux
Executing a Windows command in Linux

Translation Issues

There are some caveats to passing command output back and forth between bash and PowerShell.

One big problem is how PowerShell and bash return information. PowerShell is an object-oriented programming language while bash is a string manipulation tool. Any PowerShell objects piped to bash will flattened as a string. Conversely, any bash output piped to PowerShell will be converted to a string object.

You can get around the behavior somewhat by converting or explicitly casting object types in PowerShell like in the example below. But if you are expecting to pass objects between PowerShell and WSL without any extra work, you’re going to be disappointed.

Problems passing objects
Problems passing objects

By casting the bash date as the [datetime] class in PowerShell, now we have a valid PowerShell object that we can use in our script. If you are writing scripts that need to go from Windows to WSL and back again, it’s possible to do with a little massaging to the code.

Install a Windows Subsystem for Linux GUI with Xfce4

When command-line tools aren’t enough, it’s time to break out the GUIs. If you need to run a graphical utility on WSL, explore a custom distro, or you’re not familiar with bash yet, you can install a Linux GUI.

Xfce

Linux has many available desktop environments. One of the most common ones to set up for WSL is called Xfce. At the time of this writing, Xfce is at version 4. Other desktop environments are available but in this article, you’ll learn how to get Xfce4 set up.

xRDP

When you have a Linux desktop environment set up, you’ll need a service that understands the RDP protocol. In this article, we’ll focus on the xRDP server. xRDP is an open source RDP server for Linux that allows you to use RDP clients to connect to Linux just as if you can Windows hosts.

Setting Up

To access a Linux GUI from Windows with Xfce4 and xRDP, follow the instructions below. In a WSL terminal:

  1. Download and install Xfce4 – Download and install Xfce4 using the command sudo apt-get -y install xfce4 && sudo apt-get -y install xubuntu-desktop. This will take a while. Stand by.
  2. Install the xRDP server – Download and install xRDP by running sudo apt-get -y install xrdp.
  3. Configure xRDP for xfce4 – echo xfce4-session > ~/.xsession
  4. Restart xRDPsudo service xrdp restart
  5. Find the WSL distro IP addressifconfig | grep inet

At this point, you should be able to open an RDP session from Windows 10. Open up remote desktop connection window using mstsc and provide the Linux IP address found in step #5.

If all goes well, you can open an RDP connection to the Linux distro that’s running on your Windows operating system as shown below.

Windows Subsystem for Linux GUI with Xfce4 and xRDP
Windows Subsystem for Linux GUI with Xfce4 and xRDP

Tips and Tricks

Now that you know the basics of WSL and how to use it, what’s next? Fortunately there are a lot of tools that are either built for or work well with WSL.

Setting WSL Configuration Items at Bootup with wsl.conf

A configuration file exists in the WSL at /etc/wsl.conf. This file contains configuration settings that run every time the WSL distro is started. When the wsl.conf file exists, WSL will ingest any setting in this file every time the Linux distro is started.

There are a few different sections inside of the wsl.conf file you can configure.

  • Automount – Mounting drives from Windows at start
  • Network – Generate resolv.conf or the hosts file
  • Interop – Enabling or disabling interop with Windows

For more details on the wsl.conf file, check out the Microsoft Set WSL Launch Settings page.

Developing on WSL with Visual Studio Code (VS Code)

VS Code seemingly integrates with everything and WSL is no exception. From within VS Code, you can set up a workspace on your WSL Distro but manipulate it completely with VS Code on Windows. You don’t even need to have a terminal running!

To set up VS Code on Windows to work with WSL, you’ll first obviously need VS Code for Windows installed. Also be sure you have the Remote – WSL VS Code extension installed.

Once you’ve got the extension installed, you can now connect to it by opening a WSL terminal and running code <workspace>.  <Workspace> is the directory where you’d like to run VS Code from. VS Code will then detect that you are in a WSL distro, open a window, and establish a connection to to the workspace.

Confirm it worked by noticing the WSL connection icon in the lower left corner of VS Code. You should see that it has the name of your WSL distro.

Working with WSL and Visual Studio Code
Working with WSL and Visual Studio Code

You can even use the built-in terminal to interact directly with the WSL workspace. There’s no need to run a separate window for git bash commands.

Adding Windows Subsystem for Linux to the Windows Terminal

Another useful use-case of WSL is to add the WSL console it to the Windows Terminal.

From within Windows Terminal, you add each WSL distro in it’s own tab. You can also customize the look of each tab so you don’t get lost.

If you’re using a WSL distro that sets an environment variable for the user directory like UBUNTU_HOME, you can also set that as the starting directory for your terminal.

Checking the date in PowerShell and Bash
Checking the date in PowerShell and Bash

If you’d like a complete video walkthrough on setting up WSL to work with the Windows Terminal, check out the TechSnips how-to video below.

Closing Thoughts

If you’re an IT pro struggling with too many password reset requests in Active Directory, check out Specops uReset, a secure SSPR solution.

Microsoft released the WSL to allow Linux developers the ability to develop on Windows. So far, the WSL has been a step in the right direction.

It appears that the WSL is going to be a crucial component of Microsoft’s new open-source friendly strategy. If Microsoft is going to take on Apple to be the devices that developers write their code on, it’s going to be an uphill battle. But WSL is a strong card to play.

WSL brings about many many welcome benefits to developers like:

  • Significantly lighter weight than running local Linux VMs
  • Removing the overhead of installing and managing a hypervisor
  • No more requirement for multi-partitioned hard drives
  • No more complicated grub bootloaders

WSL just turns on and runs so we can all code happily ever after.

This tutorial demonstrates how to install, manage, and use a full Linux environment on your Windows 10 or Windows 11 PC with WSL2. You’ll be running a Linux kernel and executing native applications while seamlessly sharing files and services with Windows code editors and browsers.

Why Use Linux?

Your web host almost certainly uses Linux. It’s fast, open source, and runs the majority of web software including:

  • servers (Apache, NGINX, LiteSpeed, etc.)
  • language runtimes (PHP, Python, Node.js, Ruby, etc.)
  • utility libraries (image manipulation, ZIP creation, emailers, etc.)
  • databases (MySQL, MongoDB, Redis, etc.)
  • other dependencies (Elasticsearch, RabbitMQ, proxies, etc.)

Some of these dependencies may be available on Windows and macOS, but installing and maintaining identical versions is difficult. They’re often slower and you may encounter subtle differences which will not become apparent until you deploy.

Some developers use Linux as their primary desktop OS, but that may not be viable if you require non-Linux software such as Microsoft or Adobe products. Alternative options:

  • Use two PCs or dual boot on a single device. Switching between systems can be cumbersome.

  • Run a Linux virtual machine (VM) using Hyper-V, VirtualBox, Parallels, WMware, or Vagrant. This requires considerable OS resources and reasonable IT knowledge. Sharing files between systems can be awkward.

  • Run web applications in Docker containers. It’s another topic to learn and Docker itself runs natively on Linux. Both the Windows and macOS editions use Linux below the surface and the Windows edition of Docker Desktop requires WSL2.

What is the Windows Subsystem for Linux?

The Windows Subsystem for Linux (WSL) lets developers run a Linux environment directly on Windows. It’s a full Linux OS running inside Windows so you can use the same apps and files seamlessly.

WSL1 was groundbreaking and translated Linux system calls to Windows equivalents. This could be slow and some features weren’t available. WSL2 uses Hyper-V virtual machine technology so Linux compatibility is excellent and file access is up to 20x faster than before.

Windows 10 and Windows 11 Differences

Microsoft introduced WSL2 in 2020, so it was fully integrated into the Windows 11 release in October 2021.

Windows 10 requires a little more configuration effort. If you’re considering an upgrade to Windows 11, do it before installing WSL2. Windows 11 is not an improvement in some respects (I still miss taskbar icon ungrouping and dragging files!) but WSL2 seems more stable and I rarely encounter issues.

PC Requirements

WSL2 uses Hyper-V. This requires hardware virtualization support which you must enable in your BIOS.

WARNING: fiddling with your BIOS settings can trash your PC! Be careful when making changes. Consult your motherboard manufacturer’s help pages or search for online advice about your specific make and model.

Hardware virtualization is available on most modern devices, but you can check by rebooting, and opening the BIOS panels — typically by hitting the DEL, F2, or F10 key as the system starts. Look for Virtualization Technology, VTx, Secure Virtual Machine (SVM) or similar options. Ensure they are enabled, save, and reboot the machine.

Finally, ensure your C: drive has at 1GB of spare disk space — ideally more. You may be able to free up some space in Settings, System, Storage or using the Disk clean-up tool in Windows Administrative Tools.

At the time of writing, WSL2 will install Linux to your C: drive, although it’s possible to move it elsewhere after installation.

Windows Requirements

WSL2 is available with the Home, Pro, or Server editions of Windows but not Windows 10/11 S. S mode only permits apps from the Microsoft Store to “improve” security. You can switch from S mode to Windows Home/Pro using the Switch to Windows Home option in Settings > Update & Security > Activation.

Windows 10 requires the May 2020 update — that’s version 2004 or above. Choose the Settings cog from the Start menu, then select System followed by About. The Windows specifications are shown at the bottom of the panel.

Windows specifications

Use the Check for updates button in Settings, then Update & Security if it’s not installed. Some older PCs may never be compatible and it’s unlikely Microsoft will offer a patch.

Disable Fast Start-up (Optional)

Fast start-up saves the Windows session and device drivers to a file so the next boot is faster. This can cause problems for the Linux kernel, which becomes unresponsive on the next boot. If you encounter problems, disable fast start-up from the classic Control Panel > Power Options > Choose what the power buttons do:

Control Panel power options

Alternatively, create a wsl.bat file in your Startup folder (C:Users<user-name>AppDataRoamingMicrosoftWindowsStart MenuProgramsStartup) with the content:

wsl --shutdown

This will shut down WSL after Windows boots but it will restart as soon as you access a Linux distro.

Install Windows Terminal (Optional but Recommended)

Windows Terminal is a great terminal application available from the Microsoft Store or its repository at github.com/microsoft/terminal/.

Windows Terminal

Windows Terminal automatically adds WSL2 Linux distros when they’re installed and offers a configurable range of options including tabs, split views, themes, transparency, and key bindings.

Configuration is available from the Settings menu item (Ctrl + ,), the Command Palette (Ctrl + Shift + P), or the settings.json accessed at the bottom of the Settings panel.

Enable WSL2 (Windows 10)

The following instructions apply to Windows 10. They should not be necessary in Windows 11, although you should double-check if you performed a Windows 10 to 11 upgrade.

The Virtual Machine Platform and Windows Subsystem for Linux features must be enabled in Turn Windows features on or off. The panel is accessed by hitting Start and typing “features” or from the Programs and Features icon in the classic Control Panel.

enable WSL2

Alternatively, you can execute the following commands in a Windows Powershell terminal run as an Administrator:

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

Reboot Windows, then enable WSL2 as the default by entering the following command in a Windows PowerShell or command prompt:

wsl --set-default-version 2

Download Linux

Search for or locate PowerShell in the Start menu then right-click the icon and choose Run as administrator. Display a list of available Linux distros by entering:

wsl --list --online

list Linux distros

To install the default Ubuntu 20.04 distro, enter:

wsl --install

To install a specific distro by name, such as Debian, enter:

wsl --install -d Debian

Alternatively, you can install Linux distros from the Microsoft Store accessed in the Start menu. Enter “Linux” in the search box (be wary there could be software other than WSL distros).

Microsoft Store

Ubuntu is a good choice unless you have specific Linux requirements. The latest edition is installed if you click the Ubuntu icon followed the Get button.

The download and installation could take some time depending on your network and PC speed. You may be prompted to reboot yet again.

Launch Linux

A new Linux (Ubuntu) option/icon will now be available in:

  1. the Start menu
  2. Windows Terminal (if installed)
  3. Powershell — enter wsl or bash at the prompt

Third-party terminal software such as Cmder, ConEmu, or Hyper can be used by creating profiles which launch %windir%system32bash.exe ~.

The installation process will complete the first time you run the WSL2 Linux OS.

Note: you may see a message in the terminal about a kernel update. Copy the link into your browser then download and install the update. You’ll need to launch the Linux distro again to continue with the installation.

You’ll be prompted to enter a username and password. These are the credentials for Linux administration: they’re completely separate from your Windows username and password (although choosing the same ones may be practical).

Linux will eventually be ready and your terminal will show content similar to:

Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.10.102.1-microsoft-standard-WSL2 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue Aug 16 10:19:36 BST 2022

  System load:  0.0                Processes:             8
  Usage of /:   1.6% of 250.98GB   Users logged in:       0
  Memory usage: 1%                 IPv4 address for eth0: 172.21.6.83
  Swap usage:   0%


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Update Linux

There are likely to be several Linux updates. To update Ubuntu applications, enter the following commands in the Linux terminal:

sudo apt update
sudo apt upgrade

Other Linux distros will have a similar process — so check the documentation for assistance.

You can also check for Linux kernal updates from Powershell using:

wsl --update

Switch Between WSL1 and WSL2

Existing WSL1 distros can be converted to WSL2. Enter the following command in a Windows Powershell terminal to display the installed Linux distros and their WSL version:

PS C:> wsl --list --verbose

  NAME    STATE    VERSION
* Ubuntu  Running  1

(The * asterisk highlights the default Linux installation.)

To switch Ubuntu to WSL2, enter:

wsl --set-version Ubuntu 2

Similarly, to switch back to WSL1, enter:

wsl --set-version Ubuntu 1

Set a Default Linux Distribution

One Linux distribution must be set as the default when you have more than one installed. This will be used when wsl is entered in a Windows Powershell terminal.

To set the default distro, list your Linux installations:

wsl --list

and set a default with:

wsl --setdefault <DistributionName>

Ubuntu example: wsl --setdefault Ubuntu.

Run Linux as a Specific User

To run your default distribution as a specific user, enter the following command in a Windows Powershell terminal:

wsl --user <username>

A default user is defined during installation but you can create others. A root user is also created, but you should avoid using it under normal circumstances. It’s too easy to enter a dangerous command!

Move or Clone Your Linux Disk Image

Linux disk images are installed on your C: drive. Optionally, you can either:

  • move it to another drive to free up space on C:, or

  • use the same image to create multiple Linux installations (which can be useful if you need different applications and setups for different projects — although Docker may be more practical)

The following instructions presume you’re moving the Ubuntu Linux distro to D:wsl.

In a Windows Powershell terminal (not the Ubuntu terminal), enter wsl --list to view your Linux distributions, then export one by name to a backup .tar file — such as D:backupubuntu.tar:

mkdir D:backup
wsl --export Ubuntu D:backupubuntu.tar

Unregister that distro to remove it from the C: drive:

wsl --unregister Ubuntu

Enter wsl --list to verify the distro has been removed.

Import the backup into a new WSL2 distro at another location, such as D:wsl:

mkdir D:wsl
wsl --import Ubuntu D:wsl D:backupubuntu.tar

You can make any number of named clones from the same back-up. For example:

wsl --import Clone01 D:wsl D:backupubuntu.tar
wsl --import Another D:wsl D:backupubuntu.tar

Verify the WSL distro has been successfully created by entering wsl --list and launching Ubuntu from the Start menu or Windows Terminal.

At this point, Ubuntu will use root as the default user. To revert to your own account, enter the following command:

ubuntu config --default-user <yourname>

Here, <yourname> is the username you defined during installation.

For other distros that aren’t the WSL2 default, define a user by logging on to the distro and creating/editing /etc/wsl.conf:

touch /etc/wsl.conf
nano /etc/wsl.conf

Add the following lines to the file:

[user]
default=<yourname>

Save (Ctrl + O) and exit (Ctrl + X), then restart the distro in a Powershell terminal with:

wsl --terminate <distroname>

Presuming all has gone well, you can delete the backup file (D:backupubuntu.tar).

Access Linux Files from Windows

You can access WSL2 Linux files from the network path \wsl$. Enter it in the File Explorer address bar or any file open dialog.

Your installed Linux distros are listed, so you can access the Ubuntu root directory at \wsl$Ubuntu. Your personal Linux files are typically be stored at:

wsl$Ubuntuhome<yourname>

Here, <yourname> is the username you defined during installation.

It’s best to set this as the starting folder for the distro in Windows Terminal. Open the Settings, click a profile, then change the Starting directory option.

Map a Network Drive

You can mount a network drive to \wsl$Ubuntu by opening \wsl$ in File Explorer, right-clicking the Ubuntu folder, and choosing Map network drive….

map Linux drive

Unfortunately, it’s not currently possible to map deeper subdirectories. You may also encounter mapped-drive issues with some applications.

Accessing Windows Files from Linux

Windows drives are mounted in the Linux /mnt/ directory. For example, your personal Users folder at C:Users<yourname> is available at:

/mnt/c/Users/<yourname>

Here, <yourname> is your Windows username.

For ease of access, you can create a Linux symbolic link to any Windows folder from the terminal. For example, for C:projectscode:

cd ~
ln -s /mnt/c/projects/code/

A code folder will appear in your Linux home directory. Navigate to it using cd ~/code and you’ll actually be in /mnt/c/projects/code/, which maps directly to C:projectscode.

Accessing Windows files from Linux is considerably slower than using the native Linux file system. Where possible, create projects in the Linux file space, typically in your home folder (/home/<yourname>/ or ~).

Run Linux Commands from Windows

Any Linux (bash) shell command can be run from a Windows Powershell or command-line terminal using wsl:

wsl <linux-command>

For example, wsl ls -la lists all files in a Windows folder.

Run Windows Applications from Linux

Any Windows executable can be launched from Linux (it’s normally necessary to specify the .exe extension). For example, to open the current Linux directory in File Explorer, enter:

explorer.exe .

Or edit .bashrc in Notepad:

notepad.exe ~/.bashrc

Or open the a specific project directory in VS Code:

code ~/projects/mywebsite

Install Applications

Always remember you’re running two operating systems. They may be tightly integrated, but there are situations when you want an application installed everywhere.

For example, Git is useful in both Windows and Linux. The Windows edition is installed by downloading an executable. It’s best to ensure it doesn’t convert line endings:

git config --global core.autocrlf input

Git on Ubuntu is installed using:

sudo apt update
sudo apt install git-all

Similarly, you may want to test Node.js applications on both Windows and Linux. Again, Windows has a runtime installer, but the Node.js runtime is installed on Ubuntu using commands such as:

sudo apt-get install build-essential
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

git, node and npm commands will now work in either OS. Be wary that they may be different versions.

Installing Graphical Linux Applications

WSL2 allows you to run graphical X11 and Wayland Linux applications directly on Windows. You can launch Linux apps from the Start menu, pin them to the task bar, and use features such as cut and paste across applications. There are some downsides:

  • not all graphical apps will work as expected
  • some offer Linux features — such as file dialogs — that could confuse Windows users
  • there’s little benefit installing applications with native Windows editions such as Firefox, VLC, or GIMP

To proceed, install the correct GPU driver for your PC:

  • Intel GPU driver for WSL
  • AMD GPU driver for WSL
  • NVIDIA GPU driver for WSL

Then install any graphical application from the Linux terminal. For example, the GNOME Gedit text editor:

sudo apt install gedit

Launch it with:

gedit

Pin the app to your Start menu or task bar as you would with any other Windows program.

Gedit is a small application less than 2MB in download size. However, it requires GNOME and other Linux libraries, which incur several hundred megabytes of additional code on top of the chunky GPU drivers (1.1GB for Intel). Using graphical Linux apps in WSL2 only makes sense if you need to install several applications or there’s no native Windows alternative.

Installing Docker

One exception to the “install on both OSes” rule is Docker!

Docker runs applications in isolated Linux containers that are conceptually similar to lightweight virtual machines with an OS, single application, and its dependencies. Using Docker for web development provides a consistent environment that’s easy to install and works on any device.

Docker Desktop for Windows is fully WSL2-enabled:

  • there’s no need to use Hyper-V, so Docker can be installed on Windows Home
  • Docker starts and runs considerably faster when configured to use WSL2
  • installing Docker Desktop on Windows enables docker and docker-compose in both Windows and Linux

Docker Desktop suggests you use WSL2 when it’s first launched. Alternatively, you can select Settings from the Docker system tray icon menu, then choose the General tab, check Use the WSL 2 based engine, and hit Apply & Restart.

Docker WSL2 engine

Docker uses the default Linux distro, but you can also enable it in other installed distros from the WSL Integration panel in Settings, then Resources.

Launching Apache and PHP Applications Using Docker

It’s possible to install web dependencies such as Apache and PHP directly in your WSL2 Linux environment. However, Docker is safer, quicker, and more configurable: it allows you to run different versions of PHP on the same device at the same time.

In this example, you’ll create a small PHP file and run it using the latest release of PHP 7.4 in a Docker container. Ensure you’ve installed Docker Desktop for Windows and enabled WSL2 mode, then create a folder in your Linux environment with an index.php file. For example:

mkdir ~/php
cd ~/php
touch index.php

Edit index.php, perhaps using Notepad or VS Code as shown above. Add the following content, which outputs PHP status information:

<?php
phpinfo();

Run the following docker command to start a PHP 8.1-enabled Apache web server in a container which mounts files in the current host directory to /var/www/html in the container:

docker run 
  -it --rm -p 8080:80 --name php 
  -v "$PWD":/var/www/html 
  php:8.1-apache

Note: this command also works in Windows, but the reference to $PWD must be replaced by the full file path in Linux notation — such as /c/php/.

Open https://localhost:8080/ in any Windows web browser to view the output of the phpinfo() command.

To finish, press Ctrl + C in your Docker terminal to stop and delete the container.

WSL2 and localhost

Applications running on Windows, WSL2 Linux, and Docker containers are always accessed from localhost or 127.0.0.1.

The PHP example above exposed port 8080, which was mapped to port 80 in the container. Similarly, if you have Node.js installed in Linux, you can cd to any directory and start a static file server:

npx small-static-server

Open http://localhost:8888/ in a browser to view files in that directory (index.html is returned by default).

Be aware that ports available in one OS may be unavailable in the other. Port numbers less than 1,000 are only available to Linux super users. Port 80 is often reserved by the Windows Store Skype App and it can’t be changed (although the classic Desktop edition does permit it).

SSL certificates that are either self-signed or locally trusted using tools such as mkcert can be used interchangeably in both Windows and Linux environments.

VS Code WSL2 Integration

VS Code permits you to use any Windows or Linux terminal. Open the terminal with View > Terminal or Ctrl + ' then hit the down arrow next to the + icon to launch a specific type. The same menu has a Select Default Profile option where you can select the terminal to use by default.

VS Code default terminal shell

Like other applications, VS Code can directly access Linux files at \wsl$ and debuggers running on localhost. There’s no need for further extensions, but the following options permit easier Linux and Docker file management:

  • Remote – WSL: open WSL2 Linux folders
  • Remote – Containers: open or attach to a running Docker container
  • Remote Development Pack: includes both extensions above as well as Remote – SSH to connect to remote servers

After installing Remote – WSL, you can navigate to any Linux directory and launch a WSL-connected instance of VS Code:

cd ~/myproject
code .

Alternatively, click the remote window icon in the bottom left of the application, then choose a connection option.

VS Code remote window icon

Or use the new Remote Explorer icon in the Activity Bar. This allows you to choose a target type from the drop-down and connect accordingly.

VS Code Remote Explorer

The remote instance of VS Code has a separate set of extensions and settings for Linux use, but some can be globally enabled. The Extensions panel allows you to enable and configure extensions in the remote instance.

VS Code extensions

Settings are stored in your Linux ~/.vscode-server directory.

Summary

Running Linux applications on Windows used to require virtual machines, complex Samba folder shares, and lots of patience. WSL2 has revolutionized web development. It makes it easy to write code using Windows tools then run it in a production-like Linux environment. The tight integration offers the benefits of both OSes.

Further WSL2 resources:

  • Windows Subsystem for Linux Documentation
  • Developing in WSL
  • VS Code Remote development in WSL
  • Run Linux GUI apps on the Windows Subsystem for Linux

If you enjoyed this article, you might also find these resources useful too:

  • Windows Terminal: The Complete Guide
  • How to Install Docker on Windows 10 Home
  • How to Install PHP on Windows 10 (with Apache & MySQL)
  • PHP & MySQL: Novice to Ninja
  • How to Build an Image with the Dockerfile
  • Understanding Docker, Containers and Safer Software Delivery
  • Docker for Web Developers

Ever since Windows added the support for Windows Subsystem for Linux (WSL), it has become easy for admins, developers, and power users to step into the world of Linux. Before WSL support was added, users had to rely on heavy virtualization tools (such as VirtualBox, VMware Workstation, and Hyper-V) or even dual-boot configurations to run a Linux instance.

Contents

  1. Introduction to Windows Subsystem for Linux
  2. Differences between WSL and traditional VM
    • When to choose WSL 2
    • When to choose a traditional VM
  3. Prerequisites for WSL
  4. Install WSL in Windows 11
    • Manually install Windows Subsystem for Linux
  5. Install and manage Linux distros in WSL
    • List the available Linux distros
    • Install a Linux distro
    • List installed Linux distros
    • Change the default WSL Distro
    • Run and terminate Linux distros
    • Change the WSL version
    • Remove a Linux distro
    • Mount a disk in WSL 2
    • Update the WSL Linux kernel
    • File sharing between Windows and the WSL distro
  • Author
  • Recent Posts

Surender Kumar has more than twelve years of experience in server and network administration. His fields of interest are Windows Servers, Active Directory, PowerShell, web servers, networking, Linux, virtualization, and penetration testing. He loves writing for his blog.

Latest posts by Surender Kumar (see all)

  • Extending LVM space in Ubuntu — Thu, Feb 2 2023
  • Backup in Proxmox VE — Thu, Jan 26 2023
  • Snapshots in Proxmox VE — Wed, Jan 25 2023

In this article, I will cover the basics of Windows Subsystem for Linux, how to install it in Windows 11, and how to run an Ubuntu Linux container in WSL. You can also run any other version of Linux in WSL.

Introduction to Windows Subsystem for Linux

Windows Subsystem for Linux is an optional feature added to Windows 10 and later versions that allows users to run a Linux instance, including most command-line tools and applications, directly on Windows without using any traditional virtual machine or dual-boot configuration.

The WSL feature was originally added to Windows 10 version 1607 (Anniversary Update) and requires an x64-bit version of Windows. On Server operating systems, it is available for installation in Server 2016 version 1803.

The initial version of WSL (now known as WSL v1 or WSL 1) does not use the real Linux kernel. Instead, a translation layer between the Linux distribution and the Windows NT kernel translates and handles all the kernel-level operations.

Windows Subsystem for Linux v1 architecture

Windows Subsystem for Linux v1 architecture

A lot has changed since the initial launch of WSL. The newer version (known as WSL v2 or WSL 2) was released with Windows 10 version 1903, build 18362 (May 2019 Update); it included various architectural and performance improvements, particularly the use of the real Linux kernel. In WSL 2, in place of the translation layer, a real Linux kernel runs inside a lightweight utility virtual machine (VM), though this is not a traditional VM. This new architecture has resulted in a significant increase in file system performance and full system call compatibility.

Windows Subsystem for Linux v2 architecture

Windows Subsystem for Linux v2 architecture

Differences between WSL and traditional VM

While WSL 2 uses Microsoft’s Hyper-V as a hypervisor under the hood to run the utility VM, it does not require you to enable Windows’ Hyper-V role or feature; WSL works perfectly fine without it.

Please remember that WSL is not a full replacement for a traditional VM. Let me tell you why.

With the help of a hypervisor, a traditional VM creates an isolated environment in your host system that acts as a separate virtual computer with all the hardware components, such as CPU, RAM, and storage. This architecture allows a user to have a completely isolated system with a guest operating system.

However, this is not the case with WSL. While WSL 2 does run a real Linux kernel in a Hyper-V–based utility VM, it works completely behind the scenes; hence, the user does not need to install and manage the operating system or any other resources as with a traditional VM.

When to choose WSL 2

  • You have a less powerful computer.
  • You need a smaller memory or storage footprint.
  • You need faster I/O performance.
  • You don’t want to waste your time installing and managing the virtual machine.
  • You need to run a Linux distribution (distro) for development and testing purposes.

When to choose a traditional VM

  • You have a powerful computer for which resources (such as memory, CPU, and storage) are not a concern.
  • You need to run an operating system other than GNU/Linux.
  • You need a completely isolated and full-fledged system environment.
  • You want to manage the operating system, applications, and resources.
  • You want to run production-level workloads.
  • You need advanced virtualization features, such as snapshots and load balancing.

In a nutshell, both WSL and traditional VM have several pros and cons; whether you want to run a Linux distro within WSL or within a traditional virtualization platform (such as VirtualBox, Hyper-V, or VMware Workstation) depends entirely on your interest and use case. I hope the aforementioned points will help you make an informed decision.

Prerequisites for WSL

Your system must have certain prerequisites before you can run WSL.

  • It must have x64-bit and ARM64 processors.
  • To run WSL 1 on an x64 system, it must be running at least Windows 10 version 1607 (Anniversary Update).
  • To run WSL 2 on an x64 system, it must be running at least Windows 10 version 1903, build 18362 (May 2019 Update).
  • To run WSL 2 on an ARM64 system, it must be running at least Windows 10 version 2004 (build 19041 or higher).

To check the operating system version and build number, you can type the winver command in the RUN dialog and press Enter.

Install WSL in Windows 11

If your system is running Windows 10 version 2004 (build 19041 or higher) or Windows 11, Microsoft has made it incredibly easy to install WSL 2. Just launch the PowerShell console with an elevated privilege and run the following command:

wsl --install

This command enables the optional Windows features required for WSL, downloads the latest Linux kernel, sets WSL 2 as the default, and installs the Ubuntu Linux distro for you.

Install WSL using PowerShell The latest method

Install WSL using PowerShell The latest method

Once the command is finished, you can restart your computer using the Restart-Computer -Force command.

After the restart, the WSL installation will resume automatically, and you will see an Ubuntu Linux terminal, which will ask you to set the username and password for the Ubuntu WSL instance.

Ubuntu Linux running in the WSL instance

Ubuntu Linux running in the WSL instance

Manually install Windows Subsystem for Linux

If you are running an older Windows 10 build or prefer installing WSL manually, you can follow the manual installation steps laid out below.

Launch the Windows PowerShell console with an elevated privilege and run the following command:

Enable-WindowsOptionalFeature -Online -FeatureName 'Microsoft-Windows-Subsystem-Linux' -All -NoRestart

Enable the WSL feature using PowerShell The manual method

Enable the WSL feature using PowerShell The manual method

Many people still prefer using WSL 1. If you also want the same, you can restart your system at this stage and directly jump to Point 5 after rebooting. If you would rather use WSL 2, please continue to the next point. Make sure your system meets the prerequisites for running WSL 2.

The next step is to run the following command:

Enable-WindowsOptionalFeature -Online -FeatureName 'VirtualMachinePlatform' -All -NoRestart

Enable the Virtual Machine Platform feature using PowerShell The manual method

Enable the Virtual Machine Platform feature using PowerShell The manual method

Now use the following command to restart your system:

Restart-Computer -Force

After the system has restarted, download the latest kernel package for your system using the following links and install the package:

  • WSL 2 Linux kernel for x64 systems
  • WSL 2 Linux kernel for ARM64 systems

Once the kernel package is installed, your system should be running WSL 1 by default. To change the default version to WSL 2, run the following command in an elevated PowerShell console:

wsl --set-default-version 2

Now you can install any Linux distro of your choice. We will cover that in the next section.

Install and manage Linux distros in WSL

Now that you have installed WSL in your system, you can run and manage your Linux distros using PowerShell. Launch the PowerShell console with an elevated privilege and use the commands mentioned in this section.

List the available Linux distros

To see the list of all the Linux distros available for installation with WSL in the online store, you can use the following command:

wsl --list --online

WSL list online

WSL list online

You can also use the short-version command wsl -l -o, which will yield a list of all the supported Linux distros available online for installation in your system.

If you’re thinking that this list is quite small and that you cannot see the distro of your choice, rest assured that there is a way you can import any Linux distro in WSL. But that is a manual method involving multiple steps. Hopefully, we’ll discuss that later.

Install a Linux distro

Once you have the list of available distros for your system, you can use the following command for installation:

wsl --install -d kali-linux

Install a Linux distro in WSL

Install a Linux distro in WSL

This command installs Kali Linux in WSL. Of course, you can replace kali-linux with the name of the distro you want to install. Once installed, Kali Linux will be launched in a terminal.

Kali Linux in WSL Initial setup

Kali Linux in WSL Initial setup

List installed Linux distros

To see the list of all the Linux distros installed in your system, you can use the following command:

wsl --list --verbose

WSL list verbose

WSL list verbose

You can also use the short-version command wsl -l -v, which will show a list of all the Linux distros installed in your system.

To list only the instances that are currently running, you can use the following command:

wsl --list --running

List of only the running instances in WSL

List of only the running instances in WSL

Change the default WSL Distro

Have you noticed a small asterisk (*) right next to the distro name when you run the wsl -l -v command? This asterisk represents the default distro for WSL. The wsl —status command also shows the current default distro. The default distro is the one that runs when you run wsl in a command line without specifying the —distribution (or -d) parameter.

For example, in my system, docker-desktop is set as the default distro. Changing the default distro to kali-linux can be done with the following command:

wsl --set-default kali-linux

Changing the default distro in WSL

Changing the default distro in WSL

Run and terminate Linux distros

To run any distro and connect to it, you can directly use the following command in PowerShell or the command prompt:

wsl --distribution kali-linux --user surender

Run and connect a WSL distro with a specific user

Run and connect a WSL distro with a specific user

Run and connect a WSL distro with a specific user.

After using the above command, you will be directly logged in to the Kali Linux bash shell. The good thing is that your Windows drives are automatically mounted under /mnt, so you can seamlessly transfer the files between Windows and the WSL instance.

To terminate (or stop) a WSL instance, you can use the following command:

wsl --terminate kali-linux

Terminate or stop a single WSL instance

Terminate or stop a single WSL instance

This command stops a particular Linux distro (Kali Linux in this case). If your system has multiple Linux distros that are running, you can use the following command to stop them all at once:

wsl --shutdown

Stop all Linux instances using WSL shutdown

Stop all Linux instances using WSL shutdown

This command immediately stops all the running Linux distros as well as the utility VM.

Change the WSL version

As mentioned earlier, WSL 1 runs by default after installation. To change the WSL version globally, you can use the following command:

wsl --set-default-version 2

Set the default WSL version

Set the default WSL version

This command changes the default WSL to WSL 2. If you want to use WSL 1, you can type 1 instead of 2 in the command. Setting the default version to WSL 2 means that every Linux distro you will install in this system will be running in WSL 2.

Apart from changing the WSL version globally, which will affect all future WSL instances, you can set the WSL version specifically for the selected Linux distro. To do this, use the following command:

wsl --set-version kali-linux 1

This command converts the Kali Linux distro to WSL 1. It could take a while for the conversion process to finish and for the change to be verified; you will see the VERSION column of the wsl -l -v command, as shown in the following image:

Change the WSL version for a particular distro

Change the WSL version for a particular distro

Please note that the WSL instance will be stopped during the version change process.

Remove a Linux distro

To remove or uninstall a Linux distro from WSL, you need to unregister the distro using the following command:

wsl --unregister ubuntu

Unregister a distro from WSL

Unregister a distro from WSL

This command unregisters a Linux distro (Ubuntu in this case). Please note that this command will permanently erase all the data, settings, and applications within that distro.

Mount a disk in WSL 2

A cool feature available in WSL 2 is the ability to mount disks that are not supported by Windows. Please note that this feature is available only in WSL 2 running on Windows 11 (build 22000 or higher). Furthermore, the Linux distro in which you plan to mount the disk should be running in WSL 2.

This feature is particularly useful when you want to access the contents of a disk formatted with a Linux file system that is not supported by Windows. To do this, you can mount the disk using the wsl —mount command and then access the contents using WSL.

A quick overview—Windows can recognize FAT, NTFS, ReFS, exFAT, and a few other file systems, but the EXT3 and EXT4 file systems are not supported. exFAT is a cross-platform file system that is equally supported on Windows, Linux, and MacOS.

For demonstration purposes, I just connected a virtual disk formatted with the EXT4 file system. As this disk is formatted in EXT4, Windows won’t recognize it, and nothing will show up in File Explorer.

To access its contents, we can mount this storage device and make it available for Linux distros. However, before mounting the disk, we need to get the device ID for the particular disk using the following PowerShell command:

Get-CimInstance -query 'SELECT * from Win32_DiskDrive'

The Get CimInstance command used to obtain the device ID

The Get CimInstance command used to obtain the device ID

Note down the device ID returned by the above command and use it to mount the disk using the following command:

wsl --mount <DeviceID>

This command mounts the specified disk and makes it available to all the Linux distros in WSL. You can use the —bare parameter to make the disk available in WSL without mounting it to all distros. The —type parameter can be used to specify the file system for the disk. If you don’t know the file system, you can skip this parameter.

The image below displays the commands I used:

Mount and access a disk in WSL

Mount and access a disk in WSL

After entering the bash terminal, I used the lsblkid command to list the partitions available on the disk. Once I obtained the partition’s name, I mounted the partition inside the /mnt/vdisk/ directory using the regular mount command. Following this, I could read the contents of the disk.

Once you finish accessing the contents and want to unmount the disk, you can use the following command:

wsl --unmount <DeviceID>

Unmount the disk in WSL

Unmount the disk in WSL

Update the WSL Linux kernel

By default, the WSL Linux kernel will be automatically updated with Windows updates. However, to manually check and update the kernel, you can use the following commands:

wsl --status

This command shows the status of WSL, including the default distro name, WSL version, and kernel version.

wsl --update

This command forcefully checks and updates the kernel version if an update is available.

Check and update the kernel in WSL

Check and update the kernel in WSL

File sharing between Windows and the WSL distro

As mentioned above, your Windows drives are automatically mounted under /mnt inside the Linux distro; hence, you can seamlessly transfer files between Windows and the WSL instance. To transfer files, you should navigate to the mounted drive and start accessing the files as you normally would in the Linux terminal.

Access Windows drives in WSL

Access Windows drives in WSL

If you would like to view the Linux files directly inside Windows File Explorer, you can use the following command in the bash terminal of the Linux distro:

explorer.exe .

Please make sure you don’t miss the period (.) at the end of the command.

Launch File Explorer in WSL

Launch File Explorer in WSL

This will open File Explorer in Windows directly inside your current working directory in the Linux distro.

Open File Explorer in WSL

Open File Explorer in WSL

This is extremely helpful if you’re a developer. You can use this trick to manage your projects and files in Windows as well as in Linux distros, taking advantage of Linux build tools that are not normally available in Windows.

And that’s the end of this guide.

Subscribe to 4sysops newsletter!

In the next article, we will discuss how you can export your favorite Linux distro and make it available in WSL 2, assuming the distro is not available for installation from the Microsoft online store by default.

Понравилась статья? Поделить с друзьями:
  • Windows subsystem for linux 2 wsl2
  • Windows steadystate аналог для windows 7
  • Windows startup and shutdown sounds lost effect
  • Windows subsystem for android скачать торрент
  • Windows startup and shutdown sounds in synthesia