About Git Recovery

· 282 words · 2 min

We first understand the working area under Git, temporary storage area and repository concept:

The following figure shows the relationship between the workspace, the repository and staging area between the repository:

Git relationship between the workspace

Revert Workspace Changes

After edit a file, use git status to see file status. Use the following command If you want to revert those changes, this only works for tracked files(you use rm <file_name> for untracked files 😃).

# revert all changes
git checkout .

# revert changes to the specified file
git checkout -- <file_name>

Revert Temporary Area Changes

After git add . or git add <file_name>, the changes will be added into temporary area, if you want to revert those, use the following command:

# revert all changes to be committed
git reset

# revert changes to the specified file to be committed
git reset <file_name>

Revert Repository Commit

Assume your commit history like this:

$ git reflog
(HEAD -> master)
d846aa8 HEAD@{0}: commit: 5th git commit: 5 files
0c59891 HEAD@{1}: commit: 4th git commit: 4 files
4945db2 HEAD@{2}: commit: 3rd git commit: 3 files
defc4eb HEAD@{3}: commit: 2nd git commit: 2 files
2938ee3 HEAD@{4}: commit: 1st git commit: 1 file

Revert those changes use the following command:

# revert a specific commit, only the changes of 4945db2 will be reverted
git revert 4945db2

# revert all changes since a specific commit, the changes of 4945db2, 0c59891 and d846aa8 will all be reverted
git reset 4945db2