GIT fixup commands: reset, revert, reflog and amend

Shilpi Maurya
Quick Code
Published in
3 min readOct 12, 2019

Easy fix-ups for git-beginners to be more productive

In this article, we’ll take a quick look at how to reset, revert, and completely return to previous states, all with the simplicity of individual Git commands.

To discard unstaged changes

Initially, if you want to look at your unstaged changes following command can be used

git diff

If you want to undo unstaged changes in the git, then this is the command for you

git checkout -- <file name>

To discard unstaged changes in all the files in the working directory in git, following command can be used

git checkout -- .

To change commit message

In case of bad commit message, this is an instant fix up.

git commit --amend -m "commit message"

If you want a file to be part of your last commit, this is the way to do so after staging the file.

git commit --amend

Remember it is advised to use above two commands only if you haven’t pushed your changes to remote, else this will mess up history of other collaborators.

To Undo committed changes

To undo your commit and reset local to previous commit, the revert command can be used, it adds a new commit at the end of the git history.

 git revert <commit hash>

If you don’t want to commit your changes, use

git revert -n <commit hash> 

If you want to go on some previous commit, copy the hash of the commit you want to go back on and do

git reset --hard <commit hash>

Reset local branch to origin branch

Setting local branch to be just like the branch on the remote repository, can be done in two simple steps

git fetch origingit reset --hard origin/<branch-name>

Reset origin branch to local branch

If the remote history has diverged from local history, the --force flag can be used to override behavior and makes the remote repository’s branch match your local branch, deleting any upstream changes that may have occurred.

git push --force

Go back in History

Unlike real world, this is possible in git. Not only we can go back in history but can also change it by using

git reflog

git reflog shows commit in the order of when you last reference them. Running git reflog, you can see that it shows us exactly the walk through of what we have been doing.

If you want to go back, just grab the hash before you want to keep changes and you are done.

git checkout <hash>

Again, don’t change git history if other people have pulled those changes.

--

--