Today, I want to describe how to revert a commit in Git. The revert command is usually used to “take back” a commit. For example, if a commit does not fix a bug, you can revert the commit and create a new commit that fixes the issue properly.
Let’s create a small example. I create a repository and add three files to it. Unfortunately, the second file is a “bug” and needs to be reverted afterwards.
#Create a folder for our repository
$ mkdir test_repo
$ cd test_repo
# Initialize empty repository
$ git init .
# create a file and add some content
$ touch first_file.txt
$ echo "Add some content to first_file" >> first_file.txt
# Add and commit to git
$ git add .
$ git commit -m "Initial commit"
# Add a second file and commit
$ touch bug_file.txt
$ git add .
$ git commit -am "commit a bug!"
# Add a third file and commit
$ touch regular_file.txt
$ git add .
$ git commit -m "Add regular file"
Let’s check the history to get an overview of my commits.
$ git log --oneline
6c59da8 (HEAD -> master) Add regular file
ca126d3 Commit a bug!
972e4b6 Initial commit
Oh, see there is a bug in the second commit :). We need to revert the commit to fix this.
# You can use the HEAD pointer
git revert HEAD~1
# or the hash value to revert the commit
git revert ca126d3
After the execution of the command, the editor appears. You can change the commit message or leave it as it is. When you leave the editor the revert commit executes and you will see in the history, that the “bug” is reverted.
fcda64b (HEAD -> master) Revert "Commit a bug!"
6c59da8 Add regular file
ca126d3 Commit a bug!
972e4b6 Initial commit
It doesn’t matter if the commit was the last commit or it is already some commits ago. Of course, this example is a straight forward case. There exist more complex cases e.g.
- It could be that you have to resolve some conflicts before the commit can be reverted or
- you want to revert a merge.
For more detailed information visit the official documentation page or search on Stackoverflow 🙂 If you like my article hit the like button and leave a comment.