How to Undo “Git Commit --Amend” Done Instead of “Git Commit”
If you accidentally used git commit --amend
instead of git commit
, it means you modified the last commit. To undo this action, you'll need to restore the previous commit state. Here are steps to revert the changes made by git commit --amend
.
1. Identify the Previous Commit
Use git reflog
to find the commit before the amend. git reflog
tracks all changes to the HEAD, which helps in locating the previous state.
git reflog
You should see a list of entries like this:
a1b2c3d HEAD@{0}: commit (amend): Your amended commit message
e4f5g6h HEAD@{1}: commit: Your original commit message
...
Here, a1b2c3d
is the SHA of the amended commit, and e4f5g6h
is the SHA of the original commit.
2. Reset to the Original Commit
Once you've identified the SHA of the original commit (e4f5g6h
in this example), you can reset your branch to that commit.
git reset --hard e4f5g6h
3. Recover Uncommitted Changes (if needed)
If you had changes that were staged or modified before the git commit --amend
and you want to recover them:
- Check the reflog to identify the SHA where you had the desired changes.
Create a temporary branch from that SHA (optional, for safety):
git checkout -b temp-branch a1b2c3d
Cherry-pick the commit to your current branch:
git checkout your-current-branch git cherry-pick a1b2c3d
Alternatively, if you know the changes are lost after the reset, you can use git reset --soft
to avoid losing any uncommitted changes:
git reset --soft e4f5g6h
This command keeps your changes in the staging area, allowing you to commit them again correctly.
Summary
- View the reflog to find the original commit SHA.
- Reset your branch to that commit using
git reset --hard
. - Optionally, recover uncommitted changes using
git cherry-pick
orgit reset --soft
.
By following these steps, you can effectively undo an accidental git commit --amend
and restore your repository to the correct state.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github