How to With Git: Rollback Commit

How to With Git: Rollback Commit

If you’ve been making changes to your Git repo and made a mistake, it’s always nice to know you have a way to rollback your commits to get your workflow back on track. In this guide, we’ll look at the git revert command for local and remote commits to a repository.

It’s important to understand the difference between git reset and git revert before diving in.

Advantages of git revert Over git reset

Reverting has two important advantages over resetting:

  • Reverting does not change the project history, which makes it a safer operation for commits that have already been pushed to a shared repository.
  • Reverting is able to target an individual commit at an arbitrary point in the history, while if you use git reset, it can only work backward from the current commit.

Using the git revert Command to Rollback a Commit

The command syntax for git revert is:

Where the <commit> is described in any of the supported commit ID forms Git understands.

You can use git reflog to see the local Git history with its shorthand commit IDs, or use git log to find the longer-form SHA-1 commit IDs for the whole committed Git history.

The git reflog command records a chronological history of everything you have done in your local repository. Its full output might look like this:

Case 1: Reverting a Single, Local Git Commit

Now let’s say since you just added a contact-us.htm file to your project, you’ve realized you don’t really need the about-us.htm file anymore.

You can revert to the time when you made that commit and keep all changes after that by doing the following:

Git will prompt you with a new note for this revert commit, giving you a default of:

Go ahead and save that note, or create your own to complete the revert:

This will revert a specific, local commit. Newer commits and the Git history are preserved.

Case 2: Reverting a Range of Local Git Commits

To revert all the local actions from “1a890e7” up to “HEAD,” use the following:

Case 3: Reverting a Git Commit That Was Pushed

After you check out the remote repository, you can first use git revert and then push as usual:

Case 4: Reverting a Range of Git Commits That Were Pushed

We can also undo a set of pushed commits:

Just Need to Undo A Quick Local Commit? Use git reset

Sometimes if you just make a quick, local mistake you might not want to use git revert, and instead you might just want to use git reset.

Either way, you should hopefully now understand how to fix a bad commit that you accidentally made with Git. The process might seem complicated and scary at first, but it’s actually pretty simple to understand once you’ve gone through the process a few times yourself.

Jacob Nicholson

Questions or Comments? Ask Jacob!

Ask a question and Jacob will respond to you. We strive to provide the best advice on the net and we are here to help you in any way we can.