Undo the most recent local commit(s) in Git

There are few conditions here, long words in short:

Situation 1: Some changes have been made, but not git add yet. Need to restore this file to previous version.

git checkout -- your_file_name

Situation 2: Some changes have been made and already git add .

git reset HEAD your_file_name

Situation 3: Some changes have been made, git add and already git commit. Be cautious: the change will be permanently lost

git reset --hard HEAD^1

In git, there are few concepts you need to know:

  • Workspace (Working directory, working area): where your code sits
  • Local Repo: includes the all the commits, logs and etc
  • Stage area: this is the layer between workspace and local repo, contains some changes you made but haven't committed yet.

So regarding the situation 1, the changes are only made in the workspace.

Changes in Workspace

Under situation 2, the changes are made and added to the staging area

Changes in Staging area

For situation 3, changes are made, added to staging area and also added to local repo:

Changes in local repo

Reference

  • Image "Designed by stories / Freepik"
  • Needone
comments powered by Disqus