lab 16 Undoing Committed Changes


Undoing Commits 01

Sometimes you realized that a change that you have already committed was not correct and you wish to undo that commit. There are several ways of handling that issue, and the way we are going to use in this lab is always safe.

Essentially we will undo the commit by creating a new commit that reverses the unwanted changes.

Change the file and commit it. 02

Change the hello.rb file to the following.

File: hello.rb

# This is an unwanted but committed change
name = ARGV.first || "World"

puts "Hello, #{name}!"


git add hello.rb
git commit -m "Oops, we didn't want this commit"

Create a Reverting Commit 03

To undo a committed change, we need to generate a commit that removes the changes introduced by our unwanted commit.


git revert HEAD

This will pop you into the editor. You can edit the default commit message or leave it as is. Save and close the file. You should see …


$ git revert HEAD --no-edit
[master a10293f] Revert "Oops, we didn't want this commit"
 1 files changed, 1 insertions(+), 1 deletions(-)

Since we were undoing the very last commit we made, we were able to use HEAD as the argument to revert. We can revert any arbitrary commit earlier in history by simply specifying its hash value.

Note: The --no-edit in the output can be ignored. It was necessary to generate the output without opening the editor.

Check the log 04

Checking the log shows both the unwanted and the reverting commits in our repository.


git hist


$ git hist
* a10293f 2013-04-13 | Revert "Oops, we didn't want this commit" (HEAD, master) [Jim Weirich]
* 838742c 2013-04-13 | Oops, we didn't want this commit [Jim Weirich]
* 1f7ec5e 2013-04-13 | Added a comment (v1) [Jim Weirich]
* 582495a 2013-04-13 | Added a default value (v1-beta) [Jim Weirich]
* 323e28d 2013-04-13 | Using ARGV [Jim Weirich]
* 9416416 2013-04-13 | First Commit [Jim Weirich]

This technique will work with any commit (although you may have to resolve conflicts). It is safe to use even on branches that are publicly shared on remote repositories.

Up Next 05

Next, let’s look at a technique that can be used to remove the most recent commits from the repository history.

Table of Contents