Get back unused disk space from Ubuntu on WSL2

apt缓存清理

1
2
3
sudo apt-get clean
sudo apt-get autoclean
sudo apt-get autoremove

移除无用的多语言、日志、man、文档等

1
2
3
4
sudo apt install localepurge
sudo journalctl --vacuum-size 10M
sudo find /usr/share/doc -depth -type f -delete
sudo rm -rf /usr/share/man/* /usr/share/groff/* /usr/share/info/* /usr/share/lintian/* /var/cache/man/*

垃圾文件清理

1
rm -r ~/.local/share/Trash/info/ && rm -r ~/.local/share/Trash/files/ 

docker 清理

1
2
3
4
5
6
7
8
9
10
11
12
13
# 查看最大空间占用目录
sudo du -h --exclude="mnt*" --exclude="proc*" -d 1 /
# 清理 无用的volumes
docker volume prune
# 删除无用的镜像和容器及构建缓存
docker system prune
docker network prune
docker container prune
docker image prune -a
# -a would clean image without linking a container
# 删除不需要的镜像
docker images
docker rmi xxx

清理完后,压缩wsl空间。diskpart操作有风险,注意备份ext4.vhdx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 查看正在运行的wsl
wsl.exe --list --verbose

# 停止wsl
wsl.exe --shutdown

# 备份指定系统到指定位置
wsl.exe --export Ubuntu-20.04 d:\Ubuntu-20.04.tar

# 还原指定系统
wsl.exe --import Ubuntu-20.04 d:\Ubuntu-20.04.tar



# 停止wsl
wsl.exe --shutdown

diskpart


# 新命令行窗口操作 找到ext4.vhdx位置

select vdisk file="C:\Users\....ext4.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk
exit