How to use ubuntu on windows

Ubuntu is an open source software operating system that runs from the desktop, to the cloud, to all your internet connected things.

1. Overview

Windows Subsystem for Linux (WSL) allows you to install a complete Ubuntu terminal environment in minutes on your Windows machine, allowing you to develop cross-platform applications without leaving Windows.

In this tutorial, we’ll show you how to get up and running with Ubuntu on WSL. These instructions will work on both Windows 10 or Windows 11.

Whilst WSL is a powerful tool for all users, some features, such as the ability to run graphical Linux applications, are only available on Windows 11. Please check out our Windows 11 tutorial for more information.


2. Install WSL

Installing WSL is now easier than ever. Search for Windows PowerShell in your Windows search bar, then select Run as administrator.

At the command prompt type:

wsl --install

And wait for the process to complete.

For WSL to be properly activated, you will now need to restart your computer.


3. Download Ubuntu

WSL supports a variety of Linux distributions, including the latest Ubuntu release, Ubuntu 20.04 LTS and Ubuntu 18.04 LTS. You can find them by opening the Microsoft store app and searching for Ubuntu.

Choose the distribution you prefer and then click on Get as shown in the following screenshot:

Ubuntu will then install on your machine.

The one line install!

There is a single command that will install both WSL and Ubuntu at the same time.
When opening PowerShell for the first time, simply modify the initial instruction to:

wsl --install -d ubuntu

This will install both WSL and Ubuntu! Don’t forget to restart your machine before continuing.

Once installed, you can either launch the application directly from the store or search for Ubuntu in your Windows search bar.


4. Configure Ubuntu

Congratulations, you now have an Ubuntu terminal running on your Windows machine!

If Ubuntu returns an error during this initial installation, then the most common issue is that virtualisation is disabled in your device’s BIOS menu. You will need to turn this on during your device’s boot sequence. The location of this option varies by manufacturer, so you will need to refer to their documentation to find it.

Once Ubuntu has finished its initial setup you will need to create a username and password (this does not need to match your Windows user credentials).

Finally, it’s always good practice to install the latest updates with the following commands, entering your password when prompted.

sudo apt update

Then

sudo apt upgrade

Press Y when prompted.


5. Install your first package

Installing packages on Ubuntu is as easy as using a single command. Below, you will see how to install bpython, a simple python interpreter for trying out ideas, featuring some nice usability features like expected parameters and autocompletion.

To check that you have the latest package lists, type:

sudo apt update

Then install bpython:

sudo apt install bpython

To run the application type:

bpython

And you’re ready to go!


6. Customising your Terminal with Windows Terminal Preview

Since you’re likely to be using your Ubuntu terminal a fair bit, it’s always nice to do some customisation. We recommend installing Windows Terminal Preview to get the most user-friendly setup. You can find it in the Microsoft Store.

Windows Terminal allows you to open multiple Terminal instances as tabs, so you can have PowerShell running alongside Ubuntu. It also includes a number of customisation options. In the below screenshot, we’ve changed the tab name and colour, and configured the terminal appearance to use the Tango Dark theme and the Ubuntu font!

These customisations can be applied universally using the Appearance menu in Settings or to individual profiles which each have their own Appearance menu. Try it yourself to find something you feel comfortable with!


7. Enjoy Ubuntu on WSL!

That’s it! In this tutorial, you’ve seen how to install WSL and Ubuntu, set up your profile, and install your first package. You also got some tips on how to customise your experience.

We hope you enjoy working with Ubuntu inside WSL. Don’t forget to check out our blog for the latest news on all things Ubuntu.

Further Reading

  • Install Ubuntu on WSL2 on Windows 11 with GUI Support
  • Working with Visual Studio Code on Ubuntu on WSL2
  • Enabling GPU acceleration on Ubuntu on WSL2 with the NVIDIA CUDA Platform
  • Setting up WSL for Data Science
  • WSL on Ubuntu Wiki
  • Ask Ubuntu

Was this tutorial useful?

Thank you for your feedback.


Если вы только начали свой путь разработчика и до сих используете операционную систему семейства Microsoft Windows, то уже наверняка столкнулись с ситуацией, когда ваш инструментарий отличается от того, что установлено у большинства людей из этой профессии. Чаще всего проблемы начинаются при работе в командной строке. Дело в том, что Windows не является POSIX-совместимой операционной системой, поэтому в ней отсутствует базовый набор прикладных программ, который необходим для разработки.

Несмотря на все написанное дальше, наша основная рекомендация — ставить полноценный Linux-дистрибутив, например, Ubuntu и полностью погружаться в него. Подавляющее большинство веб-проектов работает под управлением Linux-систем. А постоянное использование такой системы на домашнем и рабочем компьютере равносильно погружению в языковую среду при изучении иностранных языков.

Для новичков есть способ проще и быстрее — технологии виртуализации. Об этом и поговорим.

  • Ubuntu из Microsoft Store
  • Другие способы

Ubuntu из Microsoft Store

Если вы работаете на Windows версии не ниже 10 с архитектурой x64, то можно можно воспользоваться встроенным решением и установить слой совместимости (Windows Subsystem for Linux), а затем дистрибутив на основе Ubuntu Linux через магазин приложений Microsoft Store.

Подсистема WSL поставляется вместе с Windows, но не включена по-умолчанию. Чтобы её активировать, необходимо открыть PowerShell и ввести команду:

wsl --install

Также эта команда скачивает и устанавливает дистрибутив Ubuntu Linux. Скорее всего после завершения установки потребуется перезагрузить компьютер.

После перезагрузки найдите в меню Пуск приложение Ubuntu и запустите его.

Первый запуск может вызвать ошибку Error: 0x8007007e и предложение прочитать инструкцию по её решению https://aka.ms/wslinstall. Если хотите сэкономить время, то просто запустите PowerShell (не путать с cmd) от имени администратора и выполните следующую команду:

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

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

Installing, this may take a few minutes...
Installation successful!
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:

Данные логин и пароль никак не связаны с вашим пользователем в Windows, придумайте новые и не забывайте их. Чтобы изменить пароль Ubuntu в будущем, вам пригодится команда passwd

Обратите внимание на данные официальные инструкции от Microsoft, где рассмотрены не только установка и настройка WSL и Ubuntu, но так же рассказано о настройке окружения для разработки (VSCode, Git)

  • Настройка среды разработки WSL
  • WSL + VSCode

Другие способы

Если у вас нет возможности установить WSL, то можно использовать другие способы виртуализации для установки Linux. Смотрите другие наши гайды:

  • VirtualBox
  • Vagrant

К написанию данной статьи меня побудил вопрос на Тостере, связанный с 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, поэтому буду пробовать ставить.

From decades we are using Windows and Linux which are two different platforms. Sometimes we like windows for its smooth UI features and sometimes we want to move to Linux for some security purpose. But now Microsoft started to embrace the open-source community And Ubuntu is available on Microsoft Store. That means now ubuntu can be boot in windows 10 with no partition, using a USB drive, run in a window on your Windows desktop.

With Windows 10 fall creators update version 1709 Microsoft has introduced windows subsystem for Linux as an optional feature. That means No virtual machine is required and there is no dual booting, only you have to enable this feature and download the Ubuntu app from Microsoft store to run Ubuntu desktop on windows 10

Check compatibility

Well before start You just need to make sure that a window 10 is compatible with Linux requirements. open Settings > System > About, where you’ll find the System type entry here make sure you have a “64-bit operating system”. Again run winver command to check and make sure you have the latest version of Windows 10 installed on your system.

Run using SubSystem

So, what is exactly the subsystem in Ubuntu ( Linux )? It is a “Bash”. and Bash is a running Linux System inside the windows system.

Enable Windows subsystem for Linux

Well on Windows 10 you can enable Windows Subsystem for Linux feature using a simple command line on PowerShell or from windows feature.

Method 1 PowerShell

Search for PowerShell and run as Administrator.

When it opens a window the simply type below command and press enter key.

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

You’ll be asked to confirm your choice. Type Y or press enter and reboot your system.

Method 2 – Windows Feature

  • Open control panel search for programs,
  • Select the first option programs and features
  • Now on left-hand side click on Turn Windows Features On or Off.
  • This will open the windows features screen,
  • Scroll down and Checkmark next to Windows Subsystem for Linux.
  • Click ok to download required files from Microsoft server (Make sure you have a working internet connection)

Windows subsystem for Linux

As it will take slightly much time because of having large file size, you can see the Linux will installed in the windows as it is a regular application as it is one-time installation process. Restart Windows once the install process completes.

Download a Linux system from the Windows store

Now you have to download a Linux distro like Ubuntu for Windows to enter Linux commands to do this:

  • Open Microsoft Store, and search for ubuntu
  • Select option Ubuntu 18.0 and click get it

Note: At the time of writing, there are three versions of Ubuntu available on Microsoft Store: Ubuntu, Ubuntu 16.04 and Ubuntu 18.04.

install Ubuntu on Windows 10

  • It will take some time to download the app from the Microsoft server,
  • Once it completed click on launch
  • It will ask you for creating a new username and password, you need to provide all the information.

Run Ubuntu desktop on windows 10

Note: Windows File system will be located in the MNT folder, so to edit Windows files from the Linux system,  enter CD MNT, do LS then enter CD C and another LS to locate all the files stored inside Windows.

Now, you can enjoy your Linux on Windows.

Run Linux in Virtual Machine

The term virtual seems very geeky, but it is like another operating system over an existing Operating System. That you can run Linux over windows machine using Virtualization system Hyper V or using third party virtual machine. For that, you can download and install virtual machine software like VMWare Player on windows 10 PC. After that download VMware image for Ubuntu and extract the zip file.

Now double click the extracted ubantu.vmx file and the Linux machine will load inside the VMWare player. Thus Linux is “guest” OS while windows considered as “host” OS. You can install and boot Linux every time you start your machine if it will ask you to choose whether windows Os or Linux Os. You can select whatever you want, isn’t it great to switch to any of these two OS by just reboot it once.

Here, you already have a window, then you just need to install Linux. During the process of Linux installation, the installer knows how to resize its partition with windows and set up a boot loader by the given option.

Run Linux Inside the Browser

In such Case like if you are a beginner in Linux and if you want to learn Linux command, want to secure your file access within the browser, running legacy software, JavaScript engines benchmark or to use new browser technologies, you can go for JSLinux. This is an Emulator that lets you work in a web browser. You may able to write Shell Script and Awk, master regular expression, Lookup man pages of various Linux commands, etc. And everything inside the web browser.

There are certain other tools by which the user can run Linux on Windows browser like:

Copy.sh runs Linux 2.6 where the boot time is less than one minute for Linux. You can launch other operating systems too like windows 98, Arch Linux, Kolibri OS, Linux 2.6 and 3.18, Windows 1.01, FreeDOS, OpenBSD, Solar OS.

Webminal is GNU/Linux terminal to practice the Linux command and to interact with other users around the world. You just simply need to register on the website and that is completely free. Webminal is helping students of more than 125bcontries and also practiced commands more than 1.5 million.

Tutorials Point is like CentOS where the coding group gives a platform to practice the commands on the terminal in the browser, here the terminal is faster and starts within 10 seconds. There are not just Linux Terminal but also Node.js, PHP, Ruby, Numphy, Oracle Database and many online IDEs you can be browsed.

JS/UNIX Terminal where the Operating System for the web browser is written in JavaScript. There is a guest login in this terminal to practice the commands simply.

CB.VU gives you FreeBSD 7.1 stable version.

Run Linux Using USB or CD

Now the easiest way to use ubuntu is using a USB or CD drive. Simply Paste ubuntu setup in a USB drive, insert USB stick or DVD or CD into your local machine and then restart the computer, now the computer will boot from removable media and start work on ubuntu that making any changes into the computer’s hard drive.

With a live Ubuntu, you can do almost anything you can from an installed Ubuntu:

  • Safely browse the internet without storing any history or cookie data
  • Access files and edit files stored on your computer or USB stick
  • Create new office suite documents and save them remotely
  • Fix broken configurations to get a computer running again

Isn’t it looks so flexible to use Linux without disturbing current installed Windows Operating Systems? You can try any of these options where you feel comfortable to use and can easily switch to another windows UI .

Also read:

  • How To fix Windows Store cache may be damaged On Windows 10
  • 5 solutions to fix NTFS_FILE_SYSTEM error in Windows 10/8/7
  • Fix windows license will expire soon windows 10 
  • Windows 10 local account vs Microsoft account, which one is best for you?

You can install the Ubuntu distribution alongside Windows 10 to run your favorite Linux tools without switching computers or creating a virtual machine. Microsoft is moving to get more developers to code on any platform but using Windows 10 as their main tool. However, for this to happen, the company has partnered with the guys behind Ubuntu Linux (Canonical) to expand the command line toolset on Windows 10.

Although Linux integration into Windows 10 is not included by default, installing Linux distros is not difficult once you set up the Windows Subsystem for Linux 2 (WSL2) platform on your device.

This guide will teach you the steps to install Ubuntu on Windows 10.

  • Install Ubuntu on Windows 10 from WSL
  • Install Ubuntu on Windows 10 from Microsoft Store

To install Ubuntu on Windows 10 with the WSL command, use these steps:

  1. Open Start on Windows 10.

  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.

  3. Type the following command to install the WSL and Ubuntu Linux on Windows 10 and press Enter:

    wsl --install

    Single command install WSL

  4. (Optional) Type the following command to install Ubuntu if you already have WSL installed, and press Enter:

    wsl --install -d Ubuntu
  5. (Optional) Type the following command to view all the available distros and press Enter:

    wsl --list --online 
  6. (Optional) Type the following command to install a specific version of Ubuntu on Windows 10 and press Enter:

    wsl --install -d UBUNTU-VERSION

    In the command, change “UBUNTU-VERSION” to the name of the version you want to install. This example installs version 20.04:

    wsl --install -d Ubuntu-20.04
  7. Restart your computer to finish the WSL and Ubuntu installation.

  8. Continue with the Linux distro setup as necessary.

After you complete the steps, the Linux distribution will install on your computer.

Install Ubuntu on Windows 10 from Microsoft Store

To install Ubuntu on WSL from the Microsoft Store on Windows 10, use these steps:

  1. Open Start.

  2. Search for Turn Windows Features on or off and click the top result to open the Windows Features settings.

  3. Check the “Virtual Machine Platform” option.

  4. Check the “Windows Subsystem for Linux” option.

    Enable WSL components

  5. Click the OK button.

  6. Click the Restart now button.

  7. Open the WSL store page.

  8. Click the “Get in Store app” button.

  9. Click the Install button.

    Microsoft Store install WSL

  10. Open the Ubuntu store page. For example, “Ubuntu 22.04 LTS.”

  11. Click the “Get in Store app” button.

  12. Click the Install button.

    Microsoft Store install Ubuntu

  13. Click the Open button to start Ubuntu on Windows 10.

  14. Continue with the on-screen directions to complete the setup.

Once you complete the steps, you can start using the Linux terminal on Windows 10 to access apps, such as Git, Ruby, Python, grep, awk, sed, and many more tools. For command reference, you can use this Microsoft documentation page.

We may earn commission for purchases using our links to help keep offering the free content. Privacy policy info.

All content on this site is provided with no warranties, express or implied. Use any information at your own risk. Always backup of your device and files before making any changes. Privacy policy info.

Hey guys, are you trying to install Windows Subsystem for Linux in Windows? Here is the detailed installation process.

Firstly, we need to have the following system configurations and specifications to install WSL2

  • Genuine Windows Operating System
  • For x64 systems: Version 1903 or higher and Build 18362 or higher.
  • For ARM64 systems: Version 2004 or higher and Build 19041 or higher.
  • Builds lower than 18362 do not support WSL 2. Use the Windows Update Assistant to update your version of Windows.

To see your system configuration, go to settings from the start menu – choose the system – followed by About windows specifications are shown on the panel.

STEP 1: Enable Virtual Machine feature and the WSL

Prior to installing WSL2, you need to enable the virtual machine platform optional feature and windows subsystem for Linux feature, for that you have to Go to Control panel – select programs – then choose to Turn Windows features on or off and you need to enable “Windows Subsystem for Linux” followed by “Virtual machine platform” in the newly opened windows panel.

STEP 2: Install your Linux distribution of choice and Windows Terminal

In the second step, you have to download and install Ubuntu 20.04(latest) and Windows Terminal from the windows store, once installed you can run the ubuntu as an application to configure from the start menu.

Once you open the Ubuntu App, it will ask you to set up the Username of your Ubuntu system and followed by the Password.

STEP3:  Download the latest package of Linux Kernal

Once you successfully set up a password then, you have to enable wsl2, for that we need to install the Linux kernel from the windows site, If you’re using an X64 machine please click here or if you are using an ARM64 machine please click here download.

Once the installation is complete, move to the upgrade WSL2 step, setting WSL 2 as your default version when installing new Linux distributions. (Skip this step if you want your new Linux installs to be set to WSL 1).

Step 4 – Set WSL 2 as your default version

You can see your WSl version of your running Ubuntu by following command in PowerShell

wsl -l -v

the above command will show the as like the following image

You will get version 1 as the running version.

Next, you have to set the version of your Ubuntu with the following Command

syntax
wsl --set-version <distro name> <wsl version>

# example, if you are using Ubuntu-20.04 OS, then code should be like 
wsl --set-version Ubuntu-20.04 2 

Next, you have to set the default version of your Ubuntu, for that Follow the commands

wsl --set-default-version 2

STEP5: Setup your Terminal

If you open the terminal it will load automatically to Windows Powershell but the terminal can also work with Ubuntu, Microsoft Azure, and as a command prompt. You can see those things by clicking the drow down arrow in the Terminal tab section.

and If you wish to set up your Terminal to load automatically with ubuntu or have to load your project path as default, you have to edit your settings (Shortcut: CTRL + Comma) and you can copy-paste my settings JSON. If you have any doubt, please comment on the gist itself.

Note:

explorer.exe .
## the above code will open your Ubuntu Current Path 

That’s it. You can go ahead, install ZSH, Ohmyzsh, git, ruby, rails, PostgreSQL, Redis, etc. If you need any help, you can comment below or mail me at boobalan.r@spritle.com

Ubuntu 20.04 WSL

If you want to try out the improved Windows Subsystem for Linux 2 (aka WSL 2) in the latest Windows versions here’s how — I cover everything you need to do to install it, in this post.

WSL 2 is a big upgrade to the original WSL Microsoft introduced in 2017. More than a simple version bump, WSL 2 is faster, more versatile, and uses a real Linux kernel for the first time.

Plus, new Linux kernel updates will be released as Windows 10 software updates — which is kinda crazy when you think about it!

Improved performance was Microsoft’s motivation for created the souped-up WSL2. And it figured the best way to do that was to add full system call compatibility, i.e. put a real Linux kernel right at the heart of things.

“[This] new architecture presents a better platform for the WSL team to deliver features that make WSL an amazing way to run a Linux environment in Windows,” say Microsoft of the tech.

The crazy shows no sign of abating either as Microsoft plans to let users run desktop Linux apps on Windows 10 and leverage GPU-intensive tasks.

And the best news is that it is much easier to install WSL on Windows 10, as this updated guide shows.

Ubuntu-WSL-screenshot by Balint Reczey

Requirements

To install WSL 2 on Windows 10 you need the minimum:

  • Windows 10 May 2020 (2004), Windows 10 May 2019 (1903), or Windows 10 November 2019 (1909)
  • A computer with Hyper-V Virtualization support

I’d be mighty surprised if anyone who’s reading this guide doesn’t meet those requirements but, if you don’t you can use WSL 1 rather than WSL 2.

What’s awesome is that if you use Windows 10 May 2020 (2004) update or later you can install WSL2 with a single command, or a single click — no hassle.

Installing WSL 2 on OS Build 2004 (or later)

a screenshot of the windows command prompt and the new wsl install command
Single command easy

To install WSL 2 on Windows 10 OS Build 2004 or later you can open a command prompt (with Administrator permissions) and type in the following command:

wsl.exe --install

As soon as you hit enter the process gets to work enabling WSL, any optional features required, fetches the latest WSL Linux kernel version, and installs Ubuntu as the default distro:

The process is fast

Once done, reboot your computer. Log in to Windows 10 and the command prompt will open again. This time you’ll be walked through setting up Ubuntu with a username and password (these don’t need to be the same as your Windows username and password).

Once done you can you can launch the ‘Ubuntu’ app from the Start Menu to get started, or install the Microsoft Terminal app to start exploring your newly-installed Ubuntu install — don’t forget to run an apt update && apt upgrade though — this is a REAL Ubuntu system, after all!

Install WSL 2 (Old Method)

If you use an older version of Windows 10 you can still install WSL 2 (Microsoft backported WSL 2 to older versions of Windows 10 in Windows Update KB4566116) but the process isn’t as simple as in the 2004 update.

To install WSL 2 on Windows 10 (OS Build 1909 or 1903) you need to follow 4 steps:

  1. Enable WSL 2
  2. Enable ‘Virtual Machine Platform’ 
  3. Set WSL 2 as default
  4. Install a Linux distro

I walk through each step in turn below. I recommend using the PowerShell app, which you need to run as an administrator. You can find PowerShell in the Windows Start Menu.

Note: it is possible to install WSL 1 using a GUI too but it’s much faster to use the command line, and since WSL is a CLI tool it kinda makes sense too!

Step 1. Enable WSL

Regardless of which version of WSL you want to use you first need to enable it. To do this open the PowerShell tool as an Administrator and run the command below. Be careful not to mistype or leave out any character in the command:

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

Only want to use WSL 1? You can skip to step 4.

Step 2. Enable ‘Virtual Machine Platform’ 

WSL 2 requires Windows 10’s “Virtual Machine Platform” feature to be enabled. This is separate from Hyper-V and hands some of the more interesting platform integrations available in the new version of the Windows Subsystem for Linux.

To enable Virtual Machine Platform on Windows 10 (2004) open PowerShell as Administrator and run:

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

To enable Virtual Machine Platform on Windows 10 (1903, 1909) open PowerShell as Administrator and run:

Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -NoRestart

To ensure all of the relevant bits and pieces fall neatly in to place you should restart your system at this point or you may find that things don’t work as intended.

Step 3. Set WSL 2 as default

Open PowerShell as Administrator and run this command to set WSL 2 as the default version of WSL:

wsl --set-default-version 2

You can (at any time) configure a distro to run in WSL 1 mode if you need to.

Step 4. Install a distro

With WSL and the necessary virtualisation tech all in place all that is left for you to do is pick and install a Linux distro from the Microsoft Store.

Several different distros are available, including OpenSUSE, Pengwin, Fedora Remix, and Alpine Linux. But my personal recommendation is (naturally) Ubuntu 20.04 LTS (though 18.04 LTS and 16.04 LTS are also available).

To install Ubuntu on Windows 10 open the Microsoft Store app, search for “Ubuntu 20.04”, and hit the “Get” button:

Ubuntu 20.04 LTS on the Microsoft Store

Whilst you in the Microsoft Store I highly recommend that you also install the open source Windows Terminal app. This tool is designed to give you the best possible WSL experience:

Windows Terminal on the Microsoft Store

5. Use WSL 2

When you installed Ubuntu (or a different Linux distro) a shortcut was added to the Start Menu. Use this to “open” Ubuntu (or whichever distro you chose). The first time you run the distro things will seem a little slow. This is expected; the distro has to unpack and decompress all of its contents — just don’t interrupt the process.

You will also be promoted to set a username and password for use on the distro. Try to pick something you won’t forget.

Convert Ubuntu on WSL 1 to WSL 2

If you use WSL 1 you can upgrade an existing WSL 1 installation to WSL 2. To convert an existing WSL 1 distro to WSL 2 run the following in PowerShell, e..g,:

wsl.exe --set-version Ubuntu 2

You should replace ‘Ubuntu’ with the name of whichever distro your WSL 1 install runs.

Let me know if this guide worked for you in the comments!

Понравилась статья? Поделить с друзьями:

Вот еще несколько интересных статей:

  • How to use scp on windows
  • How to use roblox exploits on windows 7
  • How to use python on windows
  • How to use putty with ssh keys on windows
  • How to use pip on windows

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии