← Today I Learned

Discard file changes with git checkout

Revert changes that you made to your files.

  • development
  • git
  • gitkraken
Published

Sep 4, 2020 @ 6:53 AM

Published

Sep 18, 2020 @ 4:45 AM

Overview

Summary

I frequently discard experimental changes to files that pertain to my feature. Since I use GitKraken primarily, my process is usually to just right-click, and discard the changes to a file. Today I learned that you can use git checkout on a file to reset it's content.

Example

  1. Make a change to a file like src/pages/index.tsx and save.
  2. See your changes with git status

    $ git status

    The output is the following:

    On branch master
    Your branch is up to date with 'origin/master'.
    
    Changes not staged for commit:
     (use "git add <file>..." to update what will be committed)
     (use "git restore <file>..." to discard changes in working directory)
           modified:   src/pages/index.tsx
    
    no changes added to commit (use "git add" and/or "git commit -a")
  3. Run git checkout on the same file.

    $ git checkout src/pages/index.tsx
  4. You will see there are no changes when you run git status again.

    $ git status

    The output is the following:

    On branch master
    Your branch is up to date with 'origin/master'.
    
    nothing to commit, working tree clean

Resources

All rights reserved 2022