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>:创建分支并直接切换过去。
相关推荐
德彪稳坐倒骑驴5 小时前
Git常用命令
git
无限进步_6 小时前
【C语言&数据结构】对称二叉树:镜像世界的递归探索
c语言·开发语言·数据结构·c++·git·算法·visual studio
qq_5470261798 小时前
Git 使用指南
git
XiaoHu020710 小时前
Linux多线程(详细全解)
linux·运维·服务器·开发语言·c++·git
*才华有限公司*10 小时前
RTSP视频流播放系统
java·git·websocket·网络协议·信息与通信
juelianhuayao11 小时前
Git错误提交后如何快速删除本次commit
git
chen<>12 小时前
Git原理与应用
大数据·git·elasticsearch·svn
小兔崽子去哪了12 小时前
Git 专题
git
金米kk12 小时前
git pull时报错Your local changes to the following files would…的解决办法
git
超级罗伯特13 小时前
git一次性完成仓库下载及所有分支获取
git·git仓库拉取