什麼是 WSL

WSL 全名為 Windows Subsystem for Linux,是一款能讓使用者在 Windows 作業系統上直接執行 Linux 環境的 Windows 子系統。

WSL 的版本介紹

WSL 1

是採用系統呼叫轉譯 (System Call Translation) 的架構,將 Linux 的命令轉譯成 Windows API,這種方式是在 Windows 上模擬 Linux 的環境。因為每次的動作都要進行轉譯,因此會有執行延遲的問題。

WSL Architecture
圖片來源

WSL 2

則是採用虛擬機 (Virtual Machine) 的架構,在虛擬機內運行一個完整的 Linux 作業系統,無需透過轉譯的方式,因此執行速度大幅提升。
WSL2 Architecture
圖片來源

完整的 WSL 2 架構圖
Complete WSL2 Architecture圖片來源

安裝 WSL

  1. 在 windows 功能中打開 Virtual Machine PlatformWindows Subsystem for Linux

  2. 以系統管理員身分開啟 powershell 執行

    1
    wsl --install
  3. 重啟系統

  4. 建置第一個 Ubuntu 子系統

    • 使用 Ubuntu 22.04 版本
    1
    wsl --install -d Ubuntu-22.04

WSL 常用的命令

列出幾個比較常用的命令

列出所有可用的 Linux

1
wsl --list --online

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
The following is a list of valid distributions that can be installed.
Install using 'wsl.exe --install <Distro>'.

NAME FRIENDLY NAME
Ubuntu Ubuntu
Debian Debian GNU/Linux
kali-linux Kali Linux Rolling
Ubuntu-18.04 Ubuntu 18.04 LTS
Ubuntu-20.04 Ubuntu 20.04 LTS
Ubuntu-22.04 Ubuntu 22.04 LTS
Ubuntu-24.04 Ubuntu 24.04 LTS
OracleLinux_7_9 Oracle Linux 7.9
OracleLinux_8_7 Oracle Linux 8.7
OracleLinux_9_1 Oracle Linux 9.1
openSUSE-Leap-15.6 openSUSE Leap 15.6
SUSE-Linux-Enterprise-15-SP5 SUSE Linux Enterprise 15 SP5
SUSE-Linux-Enterprise-15-SP6 SUSE Linux Enterprise 15 SP6
openSUSE-Tumbleweed openSUSE Tumbleweed

建置 Linux 子系統

1
wsl --install -d <Distro>

列出以安裝的 Linux 子系統

1
wsl --list

Output:

1
2
Windows Subsystem for Linux Distributions:
Ubuntu-22.04 (Default)

有 (Default) 代表為預設啟動

設定預設啟動的 Linux 子系統

1
wsl --set-default <Distro>

進入 Linux 子系統

1
wsl

使用 exit 可以退出子系統

移除特定的 Linux 子系統

1
wsl --unregister <Distro>

注意! 會刪除子系統內的所有檔案

更新 WSL

1
wsl --update

查詢更多 WSL 相關命令

1
wsl --help

如何使用 WSL 進行開發

前置任務都準備完畢,終於要進入正軌了,開始進入 WSL 建置開發環境~

創建完 Linux 子系統後就可以進入到子系統內。

以 Ubuntu 22.04 作為執行範例

本機上安裝 VSCode

安裝 VSCode

安裝 VSCode 套件

安裝 WSL 套件

進入 Linux 子系統

1
wsl

創建工作目錄

1
2
mkdir ~/mywork
cd ~/mywork

預設在進入子系統時會以 Windows 的工作目錄作為啟動目錄

進入子系統的 VSCode

1
code .

透過我們在 VSCode 上安裝的 WSL 套件,讓我們可以使用 code . 來開啟當前目錄的 VSCode 編輯器

下一步就是來建置我們的 DevContainer 了

參考文獻