How to revert to a previous commit when you’ve already pushed your changes

How to revert to a previous commit when you’ve already pushed your changes

The other day I wanted to commit my changes into several separate commits however I made a mistake and pushed all of them to GitHub. I therefore wanted to revert back to a previous commit, override the current one and do the whole process again.

Here are the steps I took:

  1. Firstly, I made a new folder and copied the files from my recent commit. This is so that when I revert back to a previous commit, I will copy and paste my code so that changes show up in my git status.
  2. I needed to check the ID log of the commit I wanted to revert back to by using the following command:

git log –onelineImage for post

From this, I can see that the previous commit had the ID log of 080ebf7.

2. To go revert back to this commit, I entered:

git checkout 080ebf7Image for post

3. I then copied and pasted my code from the folder where I saved it at the beginning and did git status:

Image for post

N.B. I set my git alias (shortcut) for git status to be git st so don?t be confused by this 🙂

4. To check what branch I was on, I typed in the following command:

git branch -l -v

This is to check for local and version.

Image for post

5. I then wanted to checkout to master and then push the changes into my master branch. This is because I am working in my master branch but if you have another branch this was happening from, do checkout into that specific branch.

Image for postImage for post

Here you can see that it didn?t allow me to push it as my remote branch was behind my master branch. However what I was trying to achieve here was to override the most recent change, therefore I had to force push it:

git push -fImage for post

I did git status to check I was on the right branch:

Image for post

I then committed my changes section by section using GitHub Desktop. My git log now looks like this from log 080ebf7:

Image for post

I am now at peace with my git log ?

Massive thanks to Tomasz for helping me with this! ?

EDIT:

There is also another way to do this by using git reset however there are many modes for this which can get quite confusing unless you know what you?re doing. You can find out more by visiting the Git reset documentation and scrolling down to ?Discussion? section.

If you have found this helpful please hit that ? button and share it on social media 🙂

www.pinglinh.com

Follow me on Twitter | Check out my LinkedIn | See my GitHub

No Responses

Write a response