In the software development world, Git is a must-know tool. As a newbie developer, a proper understanding of its efficient usage can give you an advantage. Having said that, git revert and git reset are two of the most commonly used commands. Because the two commands are so similar, it might be a little confusing at times to decide which one to use in a given development scenario.
Let us have a look at the two commands to see how they vary.
Git revert
The syntax for the git revert command is: git revert [commit-identifier]
git revert
is kind of an undo command. When you git revert
a commit, git restores your working directory (current branch) to the state it was in before the specified commit was made and still keeps the commit history.
git revert
is perfect for when the commit that you’re trying to revert has already been pushed to a shared repository. It makes sure that the commit history stays intact and prevents merge complications.
To further illustrate how git revert
works, I’ve set up a simple project. As you can see from the image below, I’ve made four commits and one is a bad commit — the buggy commit.
To revert the commit, I’ll simply run the git log
to get the commit hash and then run the git commit
command.
As you can see, git revert
restores the project to the state of the initial commit before the buggy commit was made and yet still keeps all the commits.
For other command options, see the community doc.
Git reset
The syntax for the git reset command is: git reset [commit-identifier]
git reset
works like git revert
. However, in this case, it rollbacks the project to the state at which it was for the specified commit and removes all commits leading up to the specified commit from the commit history.
For example, I’ve made a fresh commit to our project.
To undo the ‘add new commit for reset’ commit and roll back to the state the project was in before the commit was made, I’ll run git reset for the commit just before it, which is bf31f2e.
As you can see, when I run git log --one line
, the ‘add new commit for reset’ has been removed from the commit history.
git reset
is perfect for when the commit you want to undo is only on your local machine and has not been pushed to a repo. However, you’ll notice that the change is not reflected in the working directory. Well, that’s because git reset only resets the current commit and the staging area. Use git revert --hard [commit-identifier]
instead.
Blog Credits: Linda Ikechukwu
Comments are closed.