Undoing Local Changes

(before staging)

Goals

  • Learn how to revert changes in the working directory

Checkout Master

Make sure you are on the latest commit in master before proceeding.

Execute:

  1. git checkout master

Change hello.rb

Sometimes you have modified a file in your local working directory and you wish to just revert to what has already been committed. The checkout command will handle that.

Change hello.rb to have a bad comment.

hello.rb

  1. # This is a bad comment. We want to revert it.
  2. name = ARGV.first || "World"
  3. puts "Hello, #{name}!"

Check the Status

First, check the status of the working directory.

Execute:

  1. git status

Output:

  1. $ git status
  2. On branch master
  3. Changes not staged for commit:
  4. (use "git add <file>..." to update what will be committed)
  5. (use "git checkout -- <file>..." to discard changes in working directory)
  6. modified: hello.rb
  7. no changes added to commit (use "git add" and/or "git commit -a")

We see that the hello.rb file has been modified, but hasn’t been staged yet.

Revert the changes in the working directory

Use the checkout command to checkout the repository’s version of the hello.rb file.

Execute:

  1. git checkout hello.rb
  2. git status
  3. cat hello.rb

Output:

  1. $ git checkout hello.rb
  2. Updated 1 path from the index
  3. $ git status
  4. On branch master
  5. nothing to commit, working tree clean
  6. $ cat hello.rb
  7. # Default is "World"
  8. name = ARGV.first || "World"
  9. puts "Hello, #{name}!"

The status command shows us that there are no outstanding changes in the working directory. And the “bad comment” is no longer part of the file contents.