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>:创建分支并直接切换过去。
相关推荐
qq_435287925 小时前
第9章 夸父逐日与后羿射日:死循环与进程终止?十个太阳同时值班的并行冲突
java·开发语言·git·死循环·进程终止·并行冲突·夸父逐日
AIMath~12 小时前
Git 子模块(Submodule)目录结构清除实战复盘
git
切糕师学AI13 小时前
Ubuntu 下 Git 完全使用指南
linux·git·ubuntu
一袋米扛几楼9814 小时前
【Git】规范化协作:详解 GitHub 工作流中的 Issue、Branch 与 Pull Request 最佳实践
前端·git·github·issue
尘埃落定wf15 小时前
# GitHub CLI:告别繁琐的 Git 命令,让开发更高效
git·github
恋喵大鲤鱼15 小时前
git clone
git·git clone
金牛IT17 小时前
Gogs 轻量级 Git 服务器搭建与使用
运维·服务器·git
Qres8211 天前
Git安装记录
git
wj3055853781 天前
Codex + Git 开发环境配置指南(WSL版)
linux·运维·git
楠枬1 天前
Git 分支管理
git