Sitemap

Git commands to undo changes

3 min readJun 19, 2023

--

Here I’ll be describing two git commands that I use commonly to undo or revert my changes.

  1. git reset

Let’s say you made following three commits on your branch and you realized you don’t need last two commits. You could use git reset to go back to your first commit.

Get the list of your commits using git log.

Press enter or click to view image in full size

If you’re pretty sure that you don’t need second and third commit at all. You can just do git reset — hard as seen below. You are back to first commit, second and third commit are completely gone.

Press enter or click to view image in full size

If you do git log, you can find that the most recent commit is commit 1.

Press enter or click to view image in full size

You can also reset last commit like below.

Press enter or click to view image in full size

If you were to do HEAD~2, it would reset last two commit.

Get Bindu Shrestha’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s see what happens when I do git reset — soft.

Press enter or click to view image in full size

As you can see second commit and third commit are undone. But this will preserve your changes in those two commits.

You can use git status command to find that the changes are present in your working area and staged. You can now decide to modify something and make a new commit or throw away changes using git reset — hard.

2. git revert

git revert can be useful when you want to remove change from a commit but you want to preserve the commit history. This is useful if your changes are already pushed to remote repository and other teammates have those changes.

Do git log to see past commits.

Press enter or click to view image in full size

I would like to revert feature 2 as below. I got conflict since I made commits to the same file after feature 2 commit.

Press enter or click to view image in full size

Once you resolve the conflict you can do git revert — continue, to proceed with the revert. While reverting you will get this message, you can just do :wq to save the revert message and quite the editor.

Press enter or click to view image in full size

--

--