Skip to content

lab 17 Undoing Committed Changes

Goals

Undoing Commits

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.

Change the hello.rb file to the following.

hello.rb

# This is an unwanted but committed change
names = ARGV || ["World"]

puts "Hello, #{names.join(" ")}!"
puts "You have #{names.length} names!"

Execute:

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

Create a Reverting Commit

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

Execute:

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 …

Output:

[main b7b217e] Revert "Oops, we didn't want this commit"
 Date: Mon Oct 24 19:02:01 2022 +0000
 1 file changed, 1 insertion(+), 1 deletion(-)

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

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

Execute:

git hist

Output:

$ git hist
* b7b217e 2022-10-24 | Revert "Oops, we didn't want this commit" (HEAD -> main) [Jim Weirich]
* a21a584 2022-10-24 | Oops, we didn't want this commit [Jim Weirich]
* 1dee7f9 2022-10-24 | Tell user how many names they have (tag: v1) [Jim Weirich]
* c72af6b 2022-10-24 | Rename variable to match its usage (tag: v1-beta) [Jim Weirich]
* 8cdd2cd 2022-10-24 | Can specify multiple names [Jim Weirich]
* 28fe396 2022-10-24 | Added a comment [Jim Weirich]
* 15c7573 2022-10-24 | Added a default value [Jim Weirich]
* 7d55044 2022-10-24 | Using ARGV [Jim Weirich]
* 91b926e 2022-10-24 | 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

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