安裝與設定 WSL 指南

這篇文章詳細介紹如何安裝和設定 Windows Subsystem for Linux (WSL),包括解決安裝錯誤、配置及常用指令範例。

舊版 WSL 的手動安裝步驟

安裝WSL

預設會安裝Ubuntu LTS。 指令需「以系統管理員身分執行」。

1
wsl.exe --install

如果出現:WslRegisterDistribution failed with error: 0x800701bc
前往官網下載 Linux 核心更新套件

設定 .wslconfig

完整的組態設定請參見官網

1
2
3
4
5
6
7
8
9
@"
[wsl2]
memory=4GB
processors=2
networkingMode=mirrored
[experimental]
autoMemoryReclaim=gradual
sparseVhd=true
"@ | Out-File "$Env:USERPROFILE\.wslconfig"

所有的組態在更改後,都需要關機並等待8秒後重啟才能更新。

1
wsl --shutdown; Start-Sleep -Seconds 8;  wsl ~

設定 wsl.config

自2023年起,systemd 現在已經預設安裝在 WSL 上的 Ubuntu。

1
$ sudo nano /etc/wsl.conf

更新套件

1
$ sudo apt update && sudo apt upgrade -y

Cheat Sheet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 列出已安裝的發行版本
wsl -l -v

# 終止所有執行中的發行版本
wsl --shutdown

# 解除安裝
wsl --unregister <DistributionName>

# 匯出散發套件
wsl --export <Distribution Name> <FileName>

# 匯入散發套件
wsl --import <Distribution Name> <InstallLocation> <FileName>

使用範例

1
2
# 統計目錄下有多少個python文件
Get-ChildItem *.py | wsl wc -l

Windows 工具必須包含副檔名、符合檔案大小寫,而且必須是可執行檔。 非可執行檔,包括批次指令碼。 CMD 原生命令 (例如 dir) 可以使用 cmd.exe /C 命令來執行,例如:cmd.exe /C dir