外观
在 Windows 和 WSL 之间共享 Git 凭据
本文介绍如何配置 Git Credential Manager (GCM),使 Windows 和 WSL 共享同一份 Git 凭据,避免在两个环境中重复输入账号密码。
前提条件
- Windows 10/11 且已安装 WSL
- Windows 侧已安装 Git for Windows(安装时选择 Git Credential Manager 作为凭据帮助程序)
1. 确认 Windows 侧 GCM 已安装
安装 Git for Windows 时,在凭据帮助程序选择步骤中选择 Git Credential Manager。
安装完成后,在 Windows PowerShell 中验证:
powershell
git config --global credential.helper应输出 manager 或 manager-core。如果未配置,手动设置:
powershell
git config --global credential.helper manager2. 在 WSL 中配置 credential helper
在 WSL 终端中,将 credential helper 指向 Windows 侧的 GCM 可执行文件。
推荐使用 Windows 8.3 短文件名格式,可以避免路径空格转义问题:
bash
git config --global credential.helper "/mnt/c/PROGRA~1/Git/mingw64/bin/git-credential-manager.exe"也可以使用完整路径(需要转义空格):
bash
git config --global credential.helper "/mnt/c/Program\ Files/Git/mingw64/bin/git-credential-manager.exe"注意:如果你的 Git for Windows 安装在非默认路径,请根据实际路径调整。可以在 Windows CMD 中执行
dir /x C:\查看短文件名。
旧版本 GCM
如果你使用的是较旧版本的 Git for Windows(GCM Core),可执行文件路径可能不同:
bash
git config --global credential.helper "/mnt/c/PROGRA~1/Git/mingw64/libexec/git-core/git-credential-manager-core.exe"3. 验证配置
在 WSL 中执行 git push 或 git clone 操作,首次会弹出 Windows 凭据管理器窗口要求输入账号密码。输入一次后,后续操作将自动使用已保存的凭据,无需重复输入。
bash
# 测试:克隆一个私有仓库
git clone https://github.com/your-username/your-private-repo.git4. 验证当前配置
bash
git config --global credential.helper输出应为 Windows 侧 GCM 的路径。
常见问题
Q: 提示找不到 credential helper 可执行文件
确认 Git for Windows 的安装路径,可在 Windows PowerShell 中执行:
powershell
where.exe git然后根据输出调整 WSL 中的路径配置。
Q: 每次 push 仍然要求输入密码
- 确认 WSL 中的
credential.helper配置正确 - 检查路径中的空格是否正确转义(使用
\转义) - 尝试先在 Windows 侧执行一次
git push保存凭据
Q: 使用 SSH 而非 HTTPS
如果使用 SSH 方式访问仓库,不需要配置 credential helper。SSH 密钥可通过以下方式共享:
- 在 WSL 中生成 SSH 密钥并添加到 Git 托管平台
- 或将 Windows 侧的
~/.ssh目录软链接到 WSL
