WSL 合集

常见问题

设置 apt 代理。编辑 /etc/apt/apt.conf,格式如下(ip 会变):

// 很奇怪,注释竟然是//开头,而不是#
Acquire::http::Proxy "http://192.168.1.56:12366/";
Acquire::https::Proxy "http://192.168.1.56:12366/";

sudo 没有 $http_proxy 代理的原因是默认不传递环境变量,使用 -E 选项传递环境变量就可以不设置上面的代理。

清华大学开源软件镜像站 https://mirrors.tuna.tsinghua.edu.cn/help/debian/

先用自己电脑给 apt 开代理,然后改镜像,安装一些 https 源需要的东西,然后 apt update。之后安装 build-essential mlocate 等等。

mlocate 安装之后:/etc/updatedb.conf 里面排除 /mnt/usr/lib/wsl 以防止扫描 C 盘和 WSL 的驱动文件(体量很大)。然后 sudo updatedb

(2025/2/13) 我新装的环境里面 update.conf 文件的内容不生效,原因不明,最后只能用命令行手动排除 Windows 的文件:sudo updatedb --prunepaths=/mnt

neovim 的配置:~/.config/nvim/init.vim

set number
set relativenumber
set expandtab
set ss=4
set tabstop=4
set shiftwidth=4

VS Code 扩展运行慢

设置通过 localhost 连接 wsl(跳过检查代理以及通过代理连接 wsl 的 vscode server)。

打开 systemd 支持后启动慢

可能是 dbus 有问题,比如我之前没有 /usr/bin/dbus-daemon,可以用 apt install --reinstall dbus 重新安装。

保持永远运行

tmux 然后使用 ctrl+b, d 来 detach。这样就模拟了一个前台任务了。

Bash

改 bash 的补全:~/.inputrc

set completion-ignore-case on

加载 ~/.bashrc 的配置:~/.bash_profile

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

环境变量

https://unix.stackexchange.com/a/64260/527050

Also a side note, /etc/profile is sourced by all shells, not just bash. The bash specific configuration file is bashrc and only sourced for interactive shells.

由于默认的 /etc/profile 有这样一段:

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

因此可以新建 /etc/profile.d/environ.sh,放入环境变量相关代码。但是该配置只在会话开始时导入,不能简单重启 bash 来更新。必要时可以自行 source。

取消 Windows 的 PATH

sudoedit /etc/wsl.conf

[interop]
appendWindowsPath = false

这样 PATH 就不会有 Windows 的了,而且 manpath 的输出结果也没有 Windows 目录。这样做 man 速度显著提升。至于 VS Code 等软件的命令,可以单独加入 PATH。

网络代理

WSL2 获取主机的 ip:(WSL1 用 http://localhost 就好)

cat /etc/resolv.conf | grep nameserver | cut -d ' ' -f 2

(2025/2/13) 在重新安装的机器上没用,下面这种有用👇。

还有一种使用 ip 命令的方案:

CLASH_IP="$(ip route show|sed -n -E 's,default via (\S+).*,\1,p')"
# 用 grep + cut 来代替 sed 也可以

git 协议(ssh)不使用 $http_proxy 代理,需要修改 ~/.ssh/config,添加

Host github.com
    User git
    ProxyCommand nc -x ${http_proxy##http://} -Xconnect %h %p

其中 nc 工具在 netcat 包中。这样 git 自己的配置文件就不用配置代理了。