从零开始:Windows 11 安装使用 WSL

环境

  • 操作系统:Windows 11 23H2
  • 命令行:Powershell 7.4.3

安装

先决条件

必须运行 Windows 10 版本 2004 及更高版本(内部版本 19041 及更高版本)或 Windows 11

运行winver查看 Windows 系统版本

在线安装(推荐)

  • 运行wsl --install [name], 这里的 name 是运行wsl -l -o查看可安装的发行版左列的NAME而不是FRIENDLY NAME
  • 如果您是第一次运行该命令, 稍等片刻后会提示重启电脑, 重启完毕后会继续完成安装
  • 稍等片刻后需要您输入非root用户名和两次相同的密码, 随后就自动进入 Linux 环境了
  • 此时先不着急后续操作, 因为该命令安装的发行版默认在 C 盘, 随着各种操作, WSL 的虚拟磁盘会越来越大, 运行exit退出 Linux 环境
  • 运行wsl --shutdown关闭所有 Linux
  • 运行wsl --export [name] [file_name], 导出发行版, 这里的 name 是运行wsl -l -v查看已安装发行版的NAME, file_name 是导出的发行版文件路径, 推荐使用绝对路径且 不要随便删除 , 因为之后无法使用wsl --install [name]安装相同版本的发行版
  • 运行wsl --unregister [name]删除指定的发行版, 这里的 name 是运行wsl -l -v查看已安装发行版的NAME
  • 运行wsl --import [name] [path] [file_name]导入发行版, 这里的 name 可以自定义, path 是安装路径, 推荐放在大容量盘, file_name 是前面导出的发行版文件路径
  • 运行wsl -l -v查看已安装的发行版, 运行wsl ~ -d [name]登录 Linux

离线安装

参考微软 wsl 文档#手动安装

其他配置(可选)

以下配置为自用备份,仅供参考

Terminal

安装或升级: 参考 terminal#install 主题: One Half Dark 字体: GeistMono Nerd Font Mono 提示符: Oh-My-Posh 无边框: Ctrl+Shift+P > 键入专注 > 回车 美化: Ctrl+逗号 > 默认值或指定选项卡 > 其他设置 > 外观 > 透明度:背景透明度80%, 启用亚克力材料打开. Ctrl+逗号 > 外观 > 应用程序主题:使用 Windows 主题, 在选项卡中使用亚克力材料:打开. 不要忘了点击下方蓝色保存按钮

.wslconfig

参考wsl-config#.wslconfig

文件位置在宿主机的%userprofile%/.wslconfig Win+E打开资源管理器, 地址栏输入%userprofile%查看路径

1
2
3
4
5
6
[wsl2]
swap=0
networkingMode=mirrored

[experimental]
autoMemoryReclaim=dropcache

wsl.conf

参考wsl-config#wsl.conf

文件位置在虚拟机的/etc/wsl.conf

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[boot]
systemd=true

[network]
hostname=dev
generateHosts=false
generateResolvConf=false

[interop]
appendWindowsPath=false

[automount]
enabled=false

.wslconfig/etc/wsl.conf需要在宿主机运行wsl --shutdown生效

resolve.conf

文件位置在虚拟机的/etc/resolv.conf

1
2
3
4
nameserver 223.5.5.5
nameserver 223.6.6.6
nameserver 2400:3200::1
nameserver 2400:3200:baba::1

vimrc

文件位置在虚拟机的$HOME/.vimrc

1
2
3
4
5
6
7
8
set tabstop=2
set shiftwidth=2
set number
set relativenumber
set expandtab
set autoindent
set smartcase
set ignorecase

Linux Shell

参考oh-my-zsh powerlevel10k

1
2
3
4
5
apt install zsh -y && sh -c "$(curl -fsSL https://install.ohmyz.sh/)"
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k
cp ~/.zshrc ~/.zshrc.bak
sed -i 's@ZSH_THEME=".*"@ZSH_THEME="powerlevel10k/powerlevel10k"@' ~/.zshrc
source .zshrc

更换镜像源

1
2
3
4
cp /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list.d/ubuntu.sources.bak
sed -i 's@//.*ubuntu.com@//mirrors.aliyun.com@g' /etc/apt/sources.list.d/ubuntu.sources
sed -i 's/http:/https:/g' /etc/apt/sources.list.d/ubuntu.sources
apt-get update