Windows 上安装 Zsh

在 Windows 环境下,通过 Git Bash 安装并配置 Zsh、Oh My Zsh 以及 Powerlevel10k 主题

PS: git bash 显示 MinGW-w64, 是基于 MSYS2 的裁剪版 不包含 pacman wget 等工具

PS: 如果要共享 MSYS2 的工具, 可以安装 MSYS2 后把 bin 目录添加到 PATH 环境变量中

1
2
nano ~/.zshrc
export PATH="/c/msys64/usr/bin:$PATH"

参考: https://gist.github.com/glenkusuma/7d7df65a89e485ec2f4690fdc88fffd6

准备工作

确保 Git 已更新到最新版本,以保证与 Zsh 软件包的兼容性

1
2
git version 2.53.0.windows.1
zsh 5.9 (x86_64-pc-cygwin)

下载并安装 Zsh

Git Bash 默认不带 Zsh,需要手动从 MSYS2 镜像中获取并安装

  1. 下载 Zsh 软件包

访问 MSYS2 软件包仓库,下载后缀为 .pkg.tar.zst 的文件

  1. 解压至 Git 目录

tar.zst, 需要 tar + zstd 解压, 要么上传到linux环境解压, 要么安装 MSYS2, 用里面的 tar 解压

1
tar xf xxx.tar.zst

复制 usr etc 目录覆盖到 C:\Program Files\Git\

  1. 设置环境变量 (PATH)
1
2
vim ~/.zshrc
export PATH="/mingw64/bin:/usr/bin:/bin:$PATH"
  1. zsh 默认启动

方法一:

  • 修改 bash.bashrc

Git Bash 启动时会读取 C:\Program Files\Git\etc\bash.bashrc为了让它能加载用户的 .bashrc,在文件末尾添加:

1
2
# Get user bash configuration ~/.bashrc
source ~/.bashrc;
  • 修改 ~/.bashrc

在你的用户主目录(~C:\Users\你的用户名)下创建或修改 .bashrc 文件,添加以下逻辑以自动跳转到 Zsh:

1
2
3
4
# Launch Zsh
if [ -t 1 ]; then
exec zsh
fi

方法二:

  • 直接启动 zsh
1
"C:/Program Files/Git/usr/bin/zsh.exe" -i -l

如果报错 /etc/profile.d/git-prompt.sh:56: command not found: shopt

1
2
mv /etc/profile.d/git-prompt.sh /etc/profile.d/git-prompt.sh.bak
curl -o /etc/profile.d/git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh

最新的 git-prompt.sh 支持zsh

  • vscode
1
2
3
4
5
6
7
"terminal.integrated.profiles.windows": {
  "zsh": {
    "path": "C:\\Program Files\\Git\\usr\\bin\\zsh.exe",
    "args": ["--login", "-i"]
  }
},
"terminal.integrated.defaultProfile.windows": "zsh",

安装 Oh My Zsh 与常用插件

  1. 安装 Oh My Zsh

在 Git Bash 中运行:

1
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
  1. 安装常用插件

运行以下命令下载语法高亮和自动补全插件:

1
2
3
4
5
# 语法高亮
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting

# 自动补全建议
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/plugins/zsh-autosuggestions

然后在 ~/.zshrc 文件中配置它们:

1
2
3
4
5
plugins=( 
    git
    zsh-syntax-highlighting
    zsh-autosuggestions
)

安装 Powerlevel10k 主题

  1. 安装主题
1
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k

~/.zshrc 中设置:

1
ZSH_THEME="powerlevel10k/powerlevel10k"
  1. 配置 P10k

重启 Shell 或运行 exec zsh,配置向导会自动启动如果未启动,运行:

1
p10k configure

提示:建议安装 Nerd Fonts (如 EnvyCodeR Nerd Font Mono) 以获得最佳图标显示效果

工具链

遇到的问题

  • ln -s 软链接变成复制
  1. ~/.zshrc文件里面加上
1
export MSYS="winsymlinks:nativestrict"
  1. 打开 git bash 需要管理员打开
  • windows 路径无法识别: 用双引号包裹
build with Hugo, theme Stack, visits 0