How to use linux in windows

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

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

К написанию данной статьи меня побудил вопрос на Тостере, связанный с 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)}\[\033[01;31m\]\h\[\033[01;34m\] \W \$\[\033[00m\] '
    else
        PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\] \[\033[01;34m\]\w \$\[\033[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 \w\a\]$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%\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs. Читать таким образом файлы можно, а вот писать — не желательно, можно поломать файловую систему. Думаю проблема в том, что 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, поэтому буду пробовать ставить.

How to Use Linux on a Windows Machine – 5 Different Approaches

As a developer, you might need to run both Linux and Windows side by side. Luckily, there are a number of ways you can get the best of both worlds without getting different computers for each operating system.

In this article, we’ll explore a few ways to use Linux on a Windows machine. Some of them are browser-based or cloud-based that do not need any installation prior to using them.

Here are the methods we’ll be discussing:

  • Dual boot
  • Windows Subsystem for Linux (WSL)
  • Virtual Machines (VM)
  • Browser-based solutions
  • Cloud-based solutions

Option 1: «Dual-boot» Linux + Windows

With dual boot, you can install Linux alongside Windows on your computer, allowing you to choose which operating system to use at startup.

This requires partitioning your hard drive and installing Linux on a separate partition. With this approach, you can only use one operating system at a time.

If this sounds like the way you want to go, here is a useful tutorial on setting up dual boot on Windows 10.

Option 2: Use Windows Subsystem for Linux (WSL)

Windows Subsystem for Linux provides a compatibility layer that lets you run Linux binary executables natively on Windows.

Using WSL has some advantages:

  • The setup for WSL is simple and not time consuming.
  • It is lightweight compared to VMs where you have to allocate resources from the host machine.
  • You don’t need to install any ISO or virtual disc image for Linux machines which tend to be heavy files.
  • You can use Windows and Linux side by side.

If this sounds like the right option for you, here is a detailed guide on how to install and use WSL.

Option 3: Use a Virtual Machine (VM)

A virtual machine (VM) is a software emulation of a physical computer system. It allows you to run multiple operating systems and applications on a single physical machine simultaneously. Here’s a detailed explanation of VMs:

You can use virtualization software such as Oracle VirtualBox or VMware to create a virtual machine running Linux within your Windows environment. This allows you to run Linux as a guest operating system alongside Windows.

VM software provides options to allocate and manage hardware resources for each VM, including CPU cores, memory, disk space, and network bandwidth. You can adjust these allocations based on the requirements of the guest operating systems and applications.

Here are some of the options available for virtualization:

  • Oracle virtual box
  • Multipass
  • VMware workstation player

Option 4: Use a Browser-based Solution

Browser based solutions are particularly useful for quick testing, learning, or accessing Linux environments from devices that don’t have Linux installed.

You can either use online code editors or web based terminals to access Linux. Note that you usually don’t have full administration privileges in these cases.

Online code editors

Online code editors offer editors with built-in Linux terminals. While their primary purpose is coding, you can also utilize the Linux terminal to execute commands and perform tasks.

Replit is an example of an online code editor, where you can write your code and access the Linux shell at the same time.

replit

Replit provides a code editor and a Linux shell.

Web-based Linux terminals

Online Linux terminals allow you to access a Linux command-line interface directly from your browser. These terminals provide a web-based interface to a Linux shell, enabling you to execute commands and work with Linux utilities.

One such example is JSLinux. The screenshot below shows a ready to use Linux environment:

jslinux

Accessing Linux via JSLinux

Option 5: Use a Cloud-based Solution

Instead of running Linux directly on your Windows machine, you can consider using cloud-based Linux environments or virtual private servers (VPS) to access and work with Linux remotely.

Services like Amazon EC2, Microsoft Azure, or DigitalOcean provide Linux instances that you can connect to from your Windows computer. Note that some of these services offer free tiers, but they are not usually free in the long run.

How to Choose the Correct Method

The choice is totally dependent on your use case. But there are some factors that may help you decide which option works the best for you. Let’s discuss them:

  • Access level/elevated privilege: If you require full administrative privileges, it is better to skip the browser-based solutions. WSL, dual booting, VMs, and cloud-based solutions provide you with full administrative control.
  • Cost: Cloud-based solutions offer services against a subscription fee. This cost varies depending on the choice of operating system, hardware specs of the machine, traffic, and so on. If you are on a tight budget, cloud-based solutions might not be the best.
  • Scalability: If you are just starting, but plan to do resource exhaustive development in the future, you can always scale up the physical specs of your machine. Some options that support upgrading are cloud-based solutions and VMs. You can add more processors or increase the RAM as per your needs.
  • Current system’s hardware specs: If your current system has lower RAM and storage, running VMs can make the system heavy. It would be better to opt for cloud-based or browser based solutions.
  • Switching: If you don’t plan to use Windows and Linux side by side, dual-boot can be a really good option. It offers a complete and focused Linux experience.

My Setup

I am using Ubuntu VM installed through VMWare workstation player. It is doing a great job as I can frequently switch between two operating systems. It was also simple to setup and I can enjoy the admin privileges as well!

my-set

Wrapping Up

I hope you found this article helpful. What’s your favorite thing you learned from this tutorial? I would love to connect with you on any of these platforms. 📧

See you in the next tutorial, happy coding 😁



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Although Windows users could also wish to run Linux software, Linux users frequently desire to run Windows applications on Linux. You can use Linux applications without leaving Windows, whether you’re searching for an improved development environment or strong command-line tools. There are several alternatives to purchasing a new laptop to run the OS for running Linux applications on Windows. Since anybody can set up a virtual machine with a free Linux distribution without the requirement for software licenses, it is simpler than running Windows software on Linux. 

There are two popular methods for running Linux software on Windows, they are

  • WSL (Windows Subsystem for Linux)
  • Virtual Machine

In this article, we’ll discuss how to implement both of these methods briefly.

Note: If you’re using Windows 11, the below steps can be omitted since Windows 11 can run Linux GUI apps out of the box.

Method 1: Windows Subsystem for Linux (WSL) 

The WSL is a feature available in Windows that’ll enable one to run the Linux file system, along with Linux command-line tools and GUI applications, directly on Windows. And they can be completely integrated with Windows tools. But the only drawback of WSL is that they are mainly targeted for command-line tools and cannot be used for graphics-intensive programs.

Step 1: Enable the Windows Subsystem for Linux optional feature

Start PowerShell or Command-Prompt with administrator privileges and enter the following command to enable the WSL services on windows, this may be enabled by default in some systems.

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

Alternatively, you can enable it using the ‘programs and features’ settings.

Step 2:  Enable the Virtual Machine platform and Install WSL2 

The virtual machine has to be enabled before installing WSL, this can be done using the following command.

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

Once it has been enabled, install WSL by entering the following command in PowerShell or Command-Prompt.

wsl --install

Set the default version of WSL to 2

wsl --set-default-version 2

Step 3: Download and Install a Linux distribution

You can download and install any distro of your choice, for the sake of convenience we’ll be installing ubuntu. Navigate to Microsoft Store and search for ‘ubuntu’ then install the application. Once downloaded open the app and follow through with the installation wizard. Once the installation process is complete you’ll be left with the following terminal. Linux Command-line tools can be executed using this terminal.

Step 4: Download and Install VcXsrv Windows X Server

The X server is a third-party display manager which is a provider of graphics resources and keyboard/mouse events. Download VcXsrv Windows X Server from the link provided – VcXsrv Windows X Server

Once the setup is complete, make sure to disable the access control option to avoid running into errors while running the GUI applications.

Step 5: Setting up the DISPLAY environment variable 

Starting the bash terminal, we have to set the DISPLAY environment variable so it uses the windows host IP address since WSL2 and Windows host doesn’t share the network device. Use any of the following commands to set the DISPLAY variable.

export DISPLAY=$(ip route|awk ‘/^default/{print $3}’):0.0

export DISPLAY=”`grep nameserver /etc/resolv.conf | sed ‘s/nameserver //’`:0″

Run the below command to check whether the variable is properly set or not.

echo $DISPLAY

The variable is reset every time a session is restarted so as to avoid running the command each and every time we open the terminal. We can add the command at the end of the /etc/bash.bashrc file. Open the bashrc file using nano or vim and then add the command at the end.

sudo nano /etc/bash.bashrc

Step 6: Create a .xsession file in the user’s home directory

The following command can be used to create a .xsession file in the user’s home directory /home/<user>/.xsession with the content xfce4-session.

echo xfce4-session > ~/.xsession

Now Windows desktop can run Linux GUI apps.

Method 2: Using a Virtual Machine

Using a Virtual Machine is the most efficient and easy way to run Linux apps on Windows, we’ll briefly discuss the installation and setting up a virtual machine with a Linux OS.

Step 1: Download and Install a Virtual Machine 

Download a virtual machine of your choice (Oracle or VMware), here we’ll be using a VMware workstation. Download the software from the below link and follow the installation process. Refer to this How to Install VirtualBox on Windows GeeksforGeeks article for setting up a virtual machine using oracle.

Download VMware Workstation.

Step 2: Download a Linux distribution of your choice

You can download any Linux distribution, below are some of the most popular choices along with their links.

  • Ubuntu
  • Pop! OS
  • Linux Mint
  • Fedora

Step 3: Installing the OS

Open VMware Workstation, and click on the ‘Create new Virtual Machine’. And then select the installer disc image option and choose the downloaded Linux operating system’s ISO file. 

Specify the disk capacity and click on next.

Name the virtual machine and move on to the next step.

 Start the virtual machine to boot up the OS and follow the installation steps. Once the installation is complete you can run any Linux GUI apps using the virtual machine.

Step 4: Starting and Running the applications

You can now run any Linux application while within the virtual machines environment, here are some examples.

$ gedit

$ sudo apt install x11-apps -y
$ xcalc

$ xclock

$ xeyes

Last Updated :
07 Nov, 2022

Like Article

Save Article

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.


1.2K
показов

1.9K
открытий

Сегодня покажу как поставить WSL (Windows Subsystem for Linux) на Windows 11

В этой статье вы узнаете:

  • Что такое WSL и для чего она нужна
  • Гайд по установке WSL
  • Настройка компилятора
  • Что делать, если WSL потребляет избыточное количество оперативной памяти

Что такое WSL и для чего она нужна

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

WSL обеспечивает совместимость с ядром Linux, что позволяет пользователям запускать большинство командной строки и приложений Linux непосредственно в Windows. Оно включает в себя поддержку большинства дистрибутивов Linux, таких как Ubuntu, Debian, Fedora и других, и предлагает доступ к огромному количеству программ и утилит, которые разработаны для Linux.

Теперь перейдём к гайду

Гайд по установке WSL

Открываем PowerShell или Terminal от имени администратора

Можно как угодно открыть эти программы, думаю, вы в курсе))

Вводим следующую команду: wsl —install

Нажимаем Enter

Ждём

Кстати говоря, по умолчанию устанавливается дистрибутив — Ubuntu

По завершении установки перезагружаем наш ПК.

Мне нравится Ubuntu, поэтому я не буду её менять, но если ты хочешь поменять дистрибутив, то вот ссылка на инструкцию.

Теперь после установки WSL необходимо создать учетную запись пользователя и пароль для установленного дистрибутива Linux (в моём случаи речь идёт про Ubuntu):

Придумай имя

Обрати внимание, что пароль при вводе не видно((

На случай, если что-то пошло не так на этапе создания учётной записи вот мини-туториал как это можно исправить.

Готово!

Важный нюанс: Windows не выполняет автоматическую установку обновлений или обновление дистрибутивов Linux. Это задача, выполнение которой большинство пользователей Linux предпочитают контролировать самостоятельно. Поэтому обновим нашу подсистему с помощью этой команды: sudo apt update && sudo apt upgrade

Я перешёл из PowerShell в Terminal, не пугайтесь, всё будет работать также))

Да, Y с большой буквы, это важно))

Настройка компилятора

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

По очереди:

sudo apt-get update

sudo apt-get install cmake gcc clang gdb build-essential

sudo apt-get install valgrind

Первая есть

Да.

Вторая

И третья

Важный момент: Проверим, установился ли у нас компилятор, должен появится номер: gcc —version

Что делать, если WSL потребляет избыточное количество оперативной памяти

Бонусом, я покажу, как снизить потребление оперативной памяти нашей подсистемой:

Вот это не есть хорошо((

Есть два пути

Путь первый:
Открываем командную строку от администратора и вставить команду
wsl —shutdown, эта команда завершит процесс VmmemWSL.

Чтобы легко открыть командную строку можно зажать кнопки Win + X > пункт PowerShell (Администратор) > команда start cmd > нажимаем Enter.

Путь второй:
Можно также ограничить ресурсы Vmmem путем создания файла %UserProfile%\.wslconfig, внутри которого прописать:

[wsl2]
memory=2GB # Ограничиваем память для WSL2 VM.processors=5 # Ограничиваем количество процессов для WSL2 VM.

Чтобы создать файл с названием .wslconfig — нужно открыть блокнот Win + R > notepad > вставить содержимое > Сохранить как > в Тип файла указать Все файлы, после указать название и сохранить.

Text Document

Всё

Более чем в два раза))

Кстати говоря, в этом файлике можете попробовать поставить значение memory равное 1, может ещё меньше будет))

На этом у меня всё, надеюсь моя статья помогла тебе решить твою проблему))

Благодарю за прочтение!

  • How to windows restore windows 10
  • How to use bluestacks on windows 10
  • Hp 1010 долго думает перед печатью windows 10
  • How to windows 10 upgrade from windows 7 to windows 10
  • How to use git on windows