需配置 git 使用 vscode 作为合并工具:执行 git config --global merge.tool vscode 和 git config --global mergetool.vscode.cmd 'code --wait --merge $base $local $remote $merged',确保 code 命令在 path 中且 --wait、--merge 参数正确,windows git bash 可能需转义变量或用绝对路径。

git config 设置 core.mergetool 为 code
VSCode 自带的冲突编辑器不是默认启用的,必须显式告诉 Git 使用 code(即 VSCode 的命令行工具)作为合并工具。关键不是安装插件,而是让 Git 能调起 VSCode 并传入正确的参数。
执行以下命令注册 mergetool:
git config --global merge.tool vscode git config --global mergetool.vscode.cmd 'code --wait --merge $BASE $LOCAL $REMOTE $MERGED'
注意三点:
-
--wait必须加,否则 Git 会立刻认为合并结束,不等你操作完就继续执行 -
--merge是 VSCode 的内置模式,它会启动四窗格视图(BASE/LOCAL/REMOTE/MERGED),缺了就退化成普通文件打开 -
$BASE等变量由 Git 提供,顺序不能错;部分系统(如 Windows Git Bash)可能需写成"\$BASE"防止提前展开
确保 code 命令在终端可用
如果运行 git mergetool 报错 command not found: code,说明 VSCode 的命令行工具没加入 PATH。
在 VSCode 中按 Ctrl+Shift+P(macOS 为 Cmd+Shift+P),输入 Shell Command: Install 'code' command in PATH 并回车执行。该操作只对当前用户生效,且需重启终端才能识别新 PATH。
验证方式:新开一个终端,运行 code --version。若返回版本号,说明已就绪;若仍失败,检查是否用了不同 shell(如 zsh vs bash),需在对应 shell 的配置文件(~/.zshrc 或 ~/.bash_profile)中重新执行安装命令。
触发合并工具时不要跳过提示
运行 git merge 或 git pull 出现冲突后,直接执行 git mergetool 即可唤起 VSCode。但常见误操作是:
- 手动用
code .打开项目,再点冲突文件——这不会进入合并模式,只是普通编辑 - 在
git status后直接git add冲突文件——Git 会报错,因为未解决的冲突文件不能被暂存 - 看到 “Hit return to start merge tool” 提示后直接回车,但 VSCode 没弹出——大概率是
code不在 PATH 或缺少--wait
正确流程是:确认有未合并的冲突(git status 显示 “both modified”),然后只运行 git mergetool,等待 VSCode 四窗格界面出现,解决后保存并关闭窗口,Git 会自动继续后续流程。
Windows 上使用 Git Bash 时的路径兼容问题
Git Bash 默认以 Unix 风格路径运行,而 VSCode 在 Windows 下实际安装路径含空格和反斜杠(如 C:\Users\Name\AppData\Local\Programs\Microsoft VS Code\Code.exe)。此时 code 命令依赖 Windows 的 PATH 注册,而非 Bash 的 /c/Users/... 形式。
若发现 code --wait --merge ... 在 Git Bash 中静默失败,可临时改用绝对路径绕过:
git config --global mergetool.vscode.cmd '"C:/Users/$USERNAME/AppData/Local/Programs/Microsoft VS Code/Code.exe" --wait --merge $BASE $LOCAL $REMOTE $MERGED'
但更稳妥的做法仍是通过 VSCode GUI 安装 shell 命令,并确保 Git Bash 启动时加载了 Windows PATH(检查 echo $PATH 是否包含 /c/Users/... 类路径)。
真正麻烦的是 WSL 环境:WSL 中的 Git 无法直接调起 Windows 版 VSCode 的 GUI,需额外配置 code-insiders 或改用 WSL 版 VSCode(code --install-extension ms-vscode-remote.remote-wsl),否则四窗格根本不会渲染。











