I accidentally amended my previous commit. The commit should have been separate to keep history of the changes I made to a particular file.
Is there a way to undo that last commit? If I do something like git reset --hard HEAD^
, the first commit also is undone.
(I have not yet pushed to any remote directories)
You can always split a commit, From the manual
Almost 9 years late to this but didn't see this variation mentioned accomplishing the same thing (it's kind of a combination of a few of these, similar to to top answer (https://stackoverflow.com/a/1459264/4642530).
Search all detached heads on branch
git reflog show origin/BRANCH_NAME --date=relative
Then find the SHA1 hash
Reset to old SHA1
git reset --hard SHA1
Then push it back up.
git push origin BRANCH_NAME
Done.
This will revert you back to the old commit entirely.
(Including the date of the prior overwritten detached commit head)
You can do below to undo your “git commit —amend”
====================================
Now your changes are as per previous. So you are done with the undo for “git commit —amend” Now you can do “git push origin “, to push to branch
Checkout to temporary branch with last commit
git branch temp HEAD@{1}
Reset last commit
git reset temp
Now, you'll have all files your commit as well as previous commit. Check status of all the files.
git status
Reset your commit files from git stage.
git reset myfile1.js
(so on)Reattach this commit
git commit -C HEAD@{1}
Add and commit your files to new commit.
Find your amended commits by:
Note: You may add
--patch
to see the body of the commits for clarity. Same asgit reflog
.then reset your HEAD to any previous commit at the point it was fine by:
Note: Replace SHA1 with your real commit hash. Also note that this command will lose any uncommitted changes, so you may stash them before. Alternatively use
--soft
instead.Then cherry-pick the other commit that you need on top of it:
Possibly worth noting that if you're still in your editor with the commit message, you can delete the commit message and it will abort the
git commit --amend
command.