Git 如何从某个 commit 新建分支

Git 如何从某个 commit 新建分支

  • 作者:吴思含(Witheart)
  • 更新时间:20250117

步骤 1: 查看 commit 历史

首先,确保你知道要基于哪个 commit 创建分支。可以使用以下命令查看 commit 历史:

bash 复制代码
git log --oneline

这会列出所有的 commit,显示每个 commit 的简短哈希值和消息。例如:

复制代码
a1b2c3d Fix bug in login
e4f5g6h Add new feature
i7j8k9l Initial commit

记下你想要基于的 commit 的哈希值(例如 a1b2c3d)。


步骤 2: 新建分支

使用以下命令从该 commit 创建一个新分支:

bash 复制代码
git branch <新分支名> <commit-hash>

例如,如果要创建一个名为 new-feature-branch 的分支,并且基于 commit a1b2c3d,可以运行:

bash 复制代码
git branch new-feature-branch a1b2c3d

步骤 3: 切换到新分支

创建分支后,切换到新分支:

bash 复制代码
git checkout new-feature-branch

或者,你也可以在创建分支时直接切换到该分支,使用:

bash 复制代码
git checkout -b <新分支名> <commit-hash>

例如:

bash 复制代码
git checkout -b new-feature-branch a1b2c3d

验证分支

切换到新分支后,可以使用以下命令查看当前所在的分支:

bash 复制代码
git branch

当前分支会被用 * 标记。


总结

  • git branch <新分支名> <commit-hash>:创建分支但不切换过去。
  • git checkout -b <新分支名> <commit-hash>:创建分支并直接切换过去。
相关推荐
_codemonster3 分钟前
Codex 核心进阶玩法(技能/MCP/派生/分叉/Git/钩子/子智能体)
git
逻极10 分钟前
Git 从入门到精通:版本控制协作实战指南
git·github·分支管理·版本控制
恋喵大鲤鱼21 分钟前
git clean
git·git clean
Patrick_Wilson1 小时前
为省一次回归测试,该不该把多个改动堆进一条分支?
git·ci/cd·架构
恋喵大鲤鱼1 小时前
git blame
git·git blame
yeflx1 小时前
Git操作
git
恋喵大鲤鱼1 小时前
git pull
git·git pull
咖啡星人k3 小时前
MonkeyCode 的 Git 集成:AI编程如何与版本控制无缝协作
git·ai编程·monkeycode
恋喵大鲤鱼4 小时前
git remote
git·git remote
恋喵大鲤鱼5 小时前
git cherry-pick
git·git cherry-pick