You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构造Git分支出现分叉(diverged)的场景以供练习?

Git分支分叉(diverged)场景构造实操步骤

前置准备

已在本地环境安装Git工具即可。


具体操作步骤

  • 第一步:创建模拟远端裸仓库
    选择一个空目录执行以下命令,用裸仓库模拟线上远端Git仓库:
    mkdir git-demo-remote && cd git-demo-remote && git init --bare && cd ..

  • 第二步:完成本地与远端的初始同步
    克隆远端仓库到本地,提交初始内容并推送,保证两端初始状态一致:

    git clone git-demo-remote git-demo-local
    cd git-demo-local
    echo "first line" > readme.md
    git add readme.md
    git commit -m "init commit"
    git push origin master
    

    此时本地master分支和远端origin/master分支指向同一提交,完全同步。

  • 第三步:模拟远端分支产生未知新提交
    新开一个终端窗口,回到初始空目录,再克隆一份仓库模拟其他设备/其他协作者的修改,直接推送到远端:

    git clone git-demo-remote git-demo-other
    cd git-demo-other
    echo "other user's modify" >> readme.md
    git add readme.md
    git commit -m "commit from other device"
    git push origin master
    

    此时远端origin/master已经新增了1个提交,而最早的本地git-demo-local仓库还未感知到这个变动。

  • 第四步:本地分支直接产生新提交构造分叉
    回到最早的git-demo-local目录,不要执行git pull/git fetch拉取远端更新,直接在本地修改提交:

    echo "local modify" >> readme.md
    git add readme.md
    git commit -m "local exclusive commit"
    
  • 第五步:验证分叉状态
    先执行git fetch origin拉取远端最新分支状态,再执行git status,即可看到官方分叉提示:

    On branch master
    Your branch and 'origin/master' have diverged,
    and have 1 and 1 different commits each, respectively.
    (use "git pull" to merge the remote branch into yours)

此时你已经成功复现了分支分叉场景,可以直接练习合并、变基、重置等各类修复方案。


内容的提问来源于stack exchange,提问作者Snowcrash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 21:54:07