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>:创建分支并直接切换过去。
相关推荐
打点计时器2 小时前
Git快速上手教程
git
我才是一卓3 小时前
linux 安装简易 git 服务端并使用
linux·运维·git
IDIOT___IDIOT5 小时前
关于 git 进行版本管理的时候 gitignore 写入忽略规则而不生效的问题
大数据·git·elasticsearch
不想看见4045 小时前
Git 误删急救手册
大数据·git·elasticsearch
偷懒下载原神5 小时前
【linux操作系统】信号
linux·运维·服务器·开发语言·c++·git·后端
IT二叔5 小时前
Git Flow03-发布流程
git
IT二叔5 小时前
Git Flow08-摘樱桃
git
「QT(C++)开发工程师」6 小时前
Git误操作急救手册大纲
git
贺小涛7 小时前
Git代码提交规范和踩坑排水明沟
大数据·git·elasticsearch
IT二叔7 小时前
Git Flow02-开发步骤
git