updated July 26, 2019

GIT revert changes tips

The article explains how to discard or revert file changes or GIT command results. Sometimes we make mistake or change our mind and want to return to the previous file state discarding the last file changes.

A file tracked by GIT could be in several states:

  1. not modified: file content is same as its last version in GIT
  2. modified: file content is changed since the last GIT commit but the changes are not scheduled for the next commit
  3. staged: file is changed since the last commit and the changes will be added into GIT on the next commit.
    The file is staged for commit with git add command.
You could see the file state running git status command. If the file is modified or staged then you see it in the command output.

1. Discard local changes in file tracked by GIT

Edited file but has not staged changes yet so the file is modified then we can discard the changes or move the file to not modified state with command:
git checkout -- file

2. Undo staging file changes for commit

Staged the file changes for commit with git add command but later decided that we don't want them in the next commit. Then we undo staging the file changes with:
git reset HEAD file

3. Revert last commit not pushed into the remote repository

Undo commit, changes are staged after:
git reset --soft HEAD~
Undo commit, changes are not staged after:
git reset HEAD~

4. Revert changes of commit

Create another commit that reverts the changes made by specified commit:
git revert commit_hash

5. Revert not staged file delete

The same as reverting not staged file changes:
git checkout -- file

6. Revert staged file delete

The same as reverting staged file changes:
git reset HEAD file

7. Discard all local not pushed commits

The command below discards all the local not pushed changes so the current state becomes the same as remote:
git reset --hard origin/current_branch
To see if there are local not pushed changes, run git fetch to sync with the remote repository and run the command:
git branch -vv