Undoing Staged Changes

(before committing)

Goals

  • Learn how to revert changes that have been staged

Change the file and stage the change

Modify the hello.rb file to have a bad comment

hello.rb

  1. # This is an unwanted but staged comment
  2. name = ARGV.first || "World"
  3. puts "Hello, #{name}!"

And then go ahead and stage it.

Execute:

  1. git add hello.rb

Check the Status

Check the status of your unwanted change.

Execute:

  1. git status

Output:

  1. $ git status
  2. On branch master
  3. Changes to be committed:
  4. (use "git reset HEAD <file>..." to unstage)
  5. modified: hello.rb

The status output shows that the change has been staged and is ready to be committed.

Reset the Staging Area

Fortunately the status output tells us exactly what we need to do to unstage the change.

Execute:

  1. git reset HEAD hello.rb

Output:

  1. $ git reset HEAD hello.rb
  2. Unstaged changes after reset:
  3. M hello.rb

The reset command resets the staging area to be whatever is in HEAD. This clears the staging area of the change we just staged.

The reset command (by default) doesn’t change the working directory. So the working directory still has the unwanted comment in it. We can use the checkout command of the previous lab to remove the unwanted change from the working directory.

Checkout the Committed Version

Execute:

  1. git checkout hello.rb
  2. git status

Output:

  1. $ git status
  2. On branch master
  3. nothing to commit, working tree clean

And our working directory is clean once again.