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>:创建分支并直接切换过去。
相关推荐
春日见7 小时前
如何创建一个PR
运维·开发语言·windows·git·docker·容器
stevenzqzq1 天前
git 常用操作
大数据·git
Curvatureflight1 天前
Git工作流最佳实践:从混乱到优雅
git
wu~9701 天前
GitHub永不遗忘,使用git push -f来覆盖的提交依旧保留
git·github
Vermouth_001 天前
git clone的时候提示access denied
git
qq_437657271 天前
清楚本地的git并重新登录
git
jiang_changsheng1 天前
工作流agent汇总分析 2
java·人工智能·git·python·机器学习·github·语音识别
顶点多余1 天前
版本控制器-git
linux·git
夔曦1 天前
Git工程日常下拉/上传完整流程(自用)
git
岱宗夫up1 天前
GitHub Desktop如何设置中文?这不是个简单问题
git·github