【Git】-- 处理 Git 提交到错误分支的问题

如果你不小心把本应提交到 test 分支的代码提交到了 master 分支(但尚未 push),可以按照以下步骤解决:

方法一(推荐):使用 git reset 和 git stash

  1. 首先,确保你在 master 分支:git checkout master

  2. 撤销最后一次提交但保留更改:git reset HEAD~1

    或者如果你想保留提交信息:git reset --soft HEAD~1

  3. 暂存你的更改:git stash

  4. 切换到 test 分支:git checkout test

  5. 应用暂存的更改:git stash pop

  6. 重新提交更改:

    复制代码
    $ git add .
    $ git commit -m "你的提交信息"

方法二:使用 git cherry-pick

如果你已经做了多个提交,或者想保留原来的提交信息:

  1. 首先切换到 test 分支:git checkout test

  2. 从 master 分支挑选提交:git cherry-pick <commit-hash>

    其中 <commit-hash> 是你在 master 上的错误提交的哈希值。

  3. 回到 master 分支并删除错误的提交:

    复制代码
    $ git checkout master
    $ git reset --hard HEAD~1

方法三:创建新分支并重置

如果你愿意,也可以:

  1. 从当前 master 创建新分支:git branch test

  2. 重置 master 到之前的状态:

    复制代码
    git checkout master
    git reset --hard origin/master
  3. 切换到 test 分支继续工作:git checkout test

推荐:方法一通常是最简单直接的解决方案。

相关推荐
echome8885 小时前
Git 日常救急:撤销提交、找回误删文件和解决冲突
git·版本控制
赵民勇10 小时前
Git命令详解
git
不老刘1 天前
Antigravity 的 New Worktree 模式:给 AI 代理一个安全的“平行工位”
人工智能·git·ai编程·antigravity
光谱SpectrAI1 天前
Windows 也中招:Git Bash 和 Node 仍信任泄露的 eMudhra 证书
git
YIN_尹1 天前
【git原理与使用】git初识与安装
大数据·git·elasticsearch
Leo_Mr1 天前
Vue3 项目配置 Git 提交规范(企业通用方案:husky + commitlint + cz-git + lint-staged)
git
jyOverQ1 天前
Git rebase 和 merge 有什么区别?什么时候该用哪个?
git
晗夜未央1 天前
跨仓库 Skill 换台电脑就失效?用 Git remote 校验项目
人工智能·git·python
Lsetea1 天前
Git访问HTTPS证书不受信任:用URL级sslCAInfo限定私有CA范围
git·https·开发工具·ssl证书·ca证书
এ慕ོ冬℘゜2 天前
Git 基础入门|和 SVN 对比 + 四大区域 + 常用命令详解
git·svn