Git examples: Resetting, Undoing and Reverting Changes

Last updated:
Table of Contents

Git version used: 2.7.4

Revert working directory to last commit

You will lose any unsaved changes!

In other words, make your working directory look exactly the same as it was after the previous commit.

$ git reset --hard HEAD~1

Revert working directory to specific commit

You will lose any unsaved changes!

That will make your working directory mirror what your Repository was like after commit <commit_hash>

$ git reset --hard <commit_hash>

Restore file from commit

Restore a file to the way it was on a given commit.

Useful for when you've modified or deleted a file by mistake.

Use git checkout <commit_hash> -- path/to/file

Example: Restore file.txt the way it was in this commit:

$ git checkout f6f207 -- file4.txt

Restore file from previous commit

Use this if you deleted/modified a file by mistake and commited it:

Use git checkout HEAD~1 -- path/to/file

Example: Restore file.txt the way it was before the previous commit:

$ git checkout HEAD~1 -- file.txt

Undo commit

No files in the working directory will be changed.

The repository will be pointing to the previous commit.

$ git reset --soft HEAD~1

Unstage changes

I.e. un-add all added files:

$ git reset --soft HEAD

Add changes to commit

Just add new files and then run git commit --amend

To add file file1.txt to the previous commit:

$ git add file1.txt
$ git commit --amend

This will open up the previous commit message in case you want to edit it or keep the same message.

Untrack file

In other words: make git forget about a file but keep it in working directory.

Use git rm --cached <myfile> and then commit


  • Remove the file from git

    $ git rm --cached myfile.txt
    rm 'myfile.txt'
  • Check it is still there (it's now untracked)

    $ git status
    On branch master
    Your branch is up-to-date with 'origin/master'.
    Changes to be committed:
      (use "git reset HEAD <file>..." to unstage)
        deleted:    myfile.txt
    Untracked files:
      (use "git add <file>..." to include in what will be committed)
  • Commit changes

    $ git commit -m "Removed myfile.txt from Git, but kept it in directory"
    1 file changed, 5 deletions(-)
    delete mode 100644 myfile.txt

(P.S. it'll always show as untracked unless you add it to .gitignore)

Undo git add

  • To make git forget about a file, see untrack file

  • To undo adding a file to a commit (but keep it tracked) use $ git reset HEAD -- path/to/file.txt

Change commit message

git commit --amend will open a text editor for you to change the last commit message

$ git commit --amend

Dialogue & Discussion