Reverting Modified in 4 Stages in Git

Jianping Zeng
3 min readMay 5, 2018

--

Git is a common tool in our development, but there are still some tricky parts we can easily ignore. In this blog, I mainly dig into how to revert in git in different stages. To make our problem simple, we only consider make changes on master branch.

In normal case, we have one step between different stages.

After we making some changes in the working directory, we can put the changed files into staging area

  1. git add xx
  2. git commit, to commit the changes into the local repository
  3. git push, to push the changed files from local repository into the remote repository

Five Statuses

As illustrated in the above figure, there is one status for each stage. Additionally, one extra stage named origin for the initial unchanged files. Therefore, there are totally five statuses. The other four are named modified, staged, commited, pushed.

How to Diff in Each Stage

In this part, we need to know how to check the “diff” in each step. We can use git -diff for each step, but the difference is that the parameters in each step are different.

Modified but Not Staged

In our working directory, we modified some file as the following and saved the file. Now the status of this this file should be modified but not staged. In this case “git -diff” can tell us which part has been modified.

Staged but Not Committed

Then we can use git -add to add this changed file to Staging Area. When we still use “git diff” but there is nothing output for this command. This is because “git diff” only check the changes between working directory and staging area. If we want to check the changes between staging area and local repository, we should use “git diff --cached”.

Commited but Not Pushed

Next, when we commited our code changes to the local repo using “git commit”, if we would like to check the change we need to use “git diff master origin/master” instead of “git diff --cache”.

How to Revert the Changes

In this part, we need to go through how to revert changes in the different stages of the last part.

Modified but Not Staged

We can use “git reset --hard” or “git checkout .” to revert the changes.

Staged but Not Committed

We can use the following two sets of commands to complete the job.

(1) git reset

git checkout .

(2) git reset --hard

Commited but Not Pushed

If you act too fast and you have already committed the changes into the local repository, then you can use the following command to revert the change.

git reset --hard origin/master

Pushed

What can you do if you make a harsh push? No worries. You only need to restore your local repository, and then push it to the remote repository.

git reset --hard Head^

git push -f

Conclusion

As we can see, “git reset --hard” is a very useful method to revert code changes in most scenarios. If you mastering it, then in most cases you can revert unnecessary code changes without troubles.

--

--