Rollback your Git repository to an earlier commit

If you need to roll your codebase back to a previous state, Git makes it easy to do this right from Git Bash.

Let’s begin!

  1. First, view the commits and their associated IDs using this command:
    git log --oneline

    If you want more details about the commits, you could leave off the --oneline argument.

  2. Find the ID of the commit that you wish to return to, and keep it for the next steps. The list should look something like this:
    b9d9c2a Change homepage from index.html to home.html
    1f85bda Fix issue with Contact Us modal
    77d9199 Add .gitignore file.
    d799606 Add new photos of development team to About Us page.
    2ed7a97 Change banner message on homepage.
    d457478 Initial commit.
  3. In our case, changing the homepage from index.html to home.html was a bad idea. I want to go back to before that change was made, so I want to go back to the commit with ID 1f85bda. We’ll use this command to do so:
    git checkout [commit-id] .

    In my example the exact command would be:

    git checkout 1f85bda .

    Note: The trailing period (.) is MANDATORY. Without it, you’ll be in a “detached head state” which means you’re not currently connected to any branch. Bottom line, a detached head state is not what we want, so make sure to include the dot.

  4. Now we’ll stage the “changes” (the change back to the previous state of the repo) and commit the changes.
    git add .
    git commit -m "Revert to [commit-id]"

    In my example I might write something like this:

    git add .
    git commit -m "Revert to 1f85bda to fix an issue where homepage had the wrong file name."

    Now if you run the git log --oneline command again you should see something like this:

    24721b8 Revert to 1f85bda to fix an issue where homepage had the wrong file name.
    b9d9c2a Change homepage from index.html to home.html
    1f85bda Fix issue with Contact Us modal
    77d9199 Add .gitignore file.
    d799606 Add new photos of development team to About Us page.
    2ed7a97 Change banner message on homepage.
    d457478 Initial commit.
  5. We have successfully traveled back in time! You might also want to push the changes (with a command such as git push origin master), so that your origin branch(es) that others might pull from in the future are also reverted to this earlier state.

Any questions? Ask below!

Leave a Comment

Your email address will not be published. Required fields are marked *