How to safely revert latest commit
Have you been in a situation when your git went horribly wrong and you need to revert desperately? I find myself in this situation once in a while and people seem to run into the same issues as well. Many new Git users may feel hopeless when they first encounter this. So in this article, I am going to show you what to do when git goes wrong and how do you fix it safely.
Long story short, I forgot to use a branch for my code and committed my changes without first doing
git pull to fetch all the changes from the remote repository. The result is:
git pushgot rejected.
git pulldoesn’t work either.
There are some good suggestions in the “hint” above. But sometimes what we want to do is just undo our latest commit. And at the same time, we may still want the changes we did from our latest commit and do not want to lose them. There are multiple ways to do this. Here is what I do:
- I check my
git log, which shows all my commit history:
- I then copy and past my latest commit ID. I do the
git diff commit_id > patchto save the diff of the latest commit to a file. This step is very important. This allows us to save the changes of our latest commit to a separate file.
- I then do a
git reset --hard HEAD^to revert to the previous commit. Note that this is a danger zone. You will lose your latest commit.
- Now when we check
git logagain, we are indeed at the previous commit:
- Then finally we are able to do a
- What do we want to do if we still want to apply the changes of our latest commit? Remember that we have saved the diff in the patch file. Here we can run
patch -p1 < patchto apply those changes. I did a dry run
patch -p1 --dry-run < patchfirst just to make sure everything works.
- Now we can see the file changes in
git diffand we can use
git commit -ato commit all the changes and
git pushto successfully push the changes.
In all, here are the git commands I did to solve the conflict and save my file changes:
# get the id of the lastest commit
git log# save the diff from the latest commit to a patch file
git diff 13fd7bc9219ee10f64b803303e6d90f94bb6e219 > patch # revert to the previous commit
git reset — hard HEAD^ # confirm that we are at the previous commit
git log # fetch changes from repo
git pull# apply file changes from the path file
patch -p1 — dry-run < patch
patch -p1 < patch # check git diff on the file changes
git diff # commit changes
git commit -a # push changes
Let me know what you usually do in this situation and if you have any suggestions. Feel free to share with me your fun experiences with git! 🙂