Git is a powerful version control system, but sometimes you may need to revert a commit. Maybe you made a mistake in your code, or maybe you want to go back to a previous version of your project. Whatever the reason, here’s how you can easily revert a Git commit.
Before starting, if you don’t have the commit hash, check out Find Git Commit Hash
Option 1: Using the “git revert” Command
The git revert
command allows you to undo a specific commit and create a new commit with the changes. This method is useful when you want to keep a record of the changes that you’re undoing.
- Check out the branch that you want to revert the commit o$ git checkout branch_name
- Run the following command to revert the commit, replacing
commit_hash
with the actual hash of the commit you want to revert:
$ git checkout branch_name
- Push the changes to your remote repository.
$ git push origin my-test-branch
Option 2: Using the “git reset” Command
The git reset
command allows you to remove one or more commits from your branch and move the branch pointer to a previous commit. This method is useful when you want to completely remove a commit and its changes from your branch.
- Check out the branch that you want to revert the commit on.
- Run the following command to reset the branch to the previous commit, replacing
commit_hash
with the actual hash of the commit you want to revert:
$ git reset --hard commit_hash
- Push the changes to your remote repository, using the
--force
option to overwrite the remote branch.
$ git push origin branch_name --force
With these two options, you can easily revert a Git commit and undo changes in your code. Whether you’re using git revert
or git reset
, you can ensure that your project stays in the desired state.