Git examples: Resetting, Undoing and Reverting Changes

Last updated:
Table of Contents

Revert working directory to last commit

$ git reset --hard HEAD~1

Revert working directory to specific commit

You don't need to use the full commit hash, just the first 6 or 7 characters will do

$ git reset --hard <commit_hash>

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

Undo commit

No files in the working directory will be changed, but the repository will be pointing to the previous commit

$ git reset --soft HEAD~1

Unstage changes

I.e. un-add added files:

$ git reset --soft HEAD

Add more changes to last 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.

Remove file from git but keep it in working directory

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


$ git rm --cached myfile.txt
rm 'myfile.txt'
$ 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)

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

Dialogue & Discussion