如何撤销误操作的“git commit --amend”而应执行“git commit”的情况

如何撤销误操作的“git commit –amend”而应执行“git commit”的情况

技术背景

在使用 Git 进行版本控制时,git commit --amend 用于修改上一次提交,包括提交信息和提交内容。但有时可能会误操作执行了 git commit --amend,而本意是执行 git commit。此时就需要撤销 git commit --amend 的操作,恢复到正确的提交状态。

实现步骤

方法一:使用 git reset --soft HEAD@{1}

  1. 移动当前 HEAD 指针
1
git reset --soft HEAD@{1}

HEAD@{1} 表示 HEAD 在移动到当前位置之前所指向的提交。此命令将 HEAD 指针移动到之前的提交,同时保留索引,以便重新进行提交。
2. 使用之前 HEAD 提交的详细信息进行提交

1
git commit -C HEAD@{1}

-C 选项会复用指定提交的日志消息和作者信息。

方法二:使用 git reflog 查找提交哈希

  1. 查看提交记录
1
git reflog

输出示例:

1
2
d0c9f22 HEAD@{0}: commit (amend): [Feature] - ABC Commit Description 
c296452 HEAD@{1}: commit: [Feature] - ABC Commit Description
  1. 软重置到指定提交
1
git reset --soft c296452

这样暂存区将包含之前意外合并到 c296452 提交中的所有更改。

方法三:使用 git resetgit cherry-pick

  1. 查找正确的提交哈希
1
git log --reflog

可添加 --patch 选项查看提交的详细内容。
2. 重置 HEAD 到指定提交

1
git reset SHA1 --hard

注意:将 SHA1 替换为实际的提交哈希,此命令会丢失未提交的更改,可先使用 git stash 保存更改。若使用 --soft 选项,则会保留最新更改,后续可进行提交。
3. 挑选其他需要的提交

1
git cherry-pick SHA1

方法四:拆分提交

  1. 开始交互式变基
1
git rebase -i commit^

commit 是要拆分的提交,任何包含该提交的提交范围都可以。
2. 标记要拆分的提交为“edit”
3. 重置 HEAD

1
git reset HEAD^

此操作会将 HEAD 回退一步,索引也会随之更新,但工作树保持不变。
4. 添加需要的更改到索引

1
git add ...

可使用 git addgit-gui 进行操作。
5. 提交当前索引

1
git commit -m "..."
  1. 重复步骤 4 和 5 直到工作树干净
  2. 继续变基
1
git rebase --continue

方法五:使用 git diffgit apply

  1. 获取提交前后的差异
1
2
git reflog
git diff before_commit_id after_commit_id > d.diff
  1. 回退到之前的提交
1
git checkout before_commit_id
  1. 应用差异
1
git apply d.diff

方法六:简单解决方案

  1. 软重置最后一次提交
1
git reset --soft HEAD^
  1. 使用新的提交信息提交暂存的更改
1
git commit -m "new commit msg"
  1. 推送更改并将此提交变基到之前修改的提交之上

方法七:使用 commit-tree 命令

1
git reset --soft "$(git commit-tree HEAD^{tree} -p HEAD@{1} -m 'Commit message of new commit')"

此命令创建一个新的提交,其树与当前 HEAD 提交相同,但父提交为原始(修改前)的提交。然后使用 git reset 将分支移动到正确的提交。

核心代码

以下是使用 git reset --soft HEAD@{1} 撤销 git commit --amend 的核心代码:

1
2
3
4
# 移动当前 head 到旧的提交
git reset --soft HEAD@{1}
# 使用之前 HEAD 提交的详细信息进行提交
git commit -C HEAD@{1}

最佳实践

  • 在执行 git commit --amend 之前,务必确认操作的正确性。
  • 定期使用 git reflog 查看提交记录,以便在出现问题时能够快速找到所需的提交哈希。
  • 在进行重要操作之前,建议先创建一个临时分支,以防止误操作导致数据丢失。

常见问题

问题一:使用 HEAD@{1} 无效

可以使用 git reflog 手动查找所需的提交哈希,然后使用 git reset --soft 进行重置。

问题二:误操作后已将提交推送到远程仓库

可按以下步骤操作:

1
2
3
4
5
6
git reset --soft <SHA BEFORE THE AMMEND>
git stash
git pull origin <your-branch> --ff-only
git stash pop
git commit -m "new commit"
git push origin <your-branch>

<SHA BEFORE THE AMMEND> 替换为修改前的提交哈希,<your-branch> 替换为实际的分支名称。

问题三:执行 git reset --hard 后丢失了未提交的更改

如果之前使用了 git stash 保存更改,可以使用 git stash pop 恢复更改。若未保存,可能无法恢复丢失的更改。


如何撤销误操作的“git commit --amend”而应执行“git commit”的情况
https://119291.xyz/posts/how-to-undo-git-commit-amend/
作者
ww
发布于
2025年5月23日
许可协议