Using git reset

Posted on October 3, 2023

The git reset command in Git allows you to undo commits and manipulate the state of your repository. It can be a tricky and potentially dangerous tool if used incorrectly, but it’s very useful for backing out changes, correcting mistakes, and rewriting commit history. This post will cover common uses cases and options for git reset.

When would you use git reset?

Some examples of when git reset comes in handy:

  • Undoing the last commit - To undo the changes from your most recent commit, use git reset --hard HEAD~1. This will move the HEAD pointer back one commit and discard those changes.

  • Undoing the last commit, but keeping the changes - To undo the changes from your most recent commit, use git reset --soft HEAD~1. This will move the HEAD pointer back one commit and but keep the changes, the changes remain staged, ready to be committed.

  • Discarding unstaged changes - If you’ve made changes to files but haven’t staged or committed them yet, you can discard the changes with git reset --hard HEAD.

  • Resetting to an older commit - To undo a series of commits, you can reset back to a previous commit by using its commit hash. For example, git reset --hard 0b7e6123 will reset to that specific commit, undoing all commits after it.

  • Unstaging files - To unstage files you previously staged with git add, use git reset HEAD <file>. The changes will be preserved but removed from the staging area.

Git reset options

The main options for git reset are:

  • --soft - Undoes commits but preserves changes in working directory.

  • --mixed - Default option. Undoes commits and unstages changes, but keeps them in working directory.

  • --hard - Completely undoes commits and any changes, leaving the working directory in a “clean” state.

Resetting vs reverting

It’s important to understand the difference between git reset and git revert. Reset erases commits from the current branch, while revert creates a new commit that reverts or rolls back an existing commit. Generally, revert is safer and avoids deleting work that hasn’t been pushed yet.

Conclusion

Git reset is a powerful command for undoing changes and altering commit history. Understanding how it works helps you recover from mistakes and maintain a linear project history. Be very careful when using git reset with the --hard option to avoid losing important work. Following best practices for using git reset will help you wield this tool more safely!

Let me know if you would like me to expand or modify this blog post draft. I can add more examples or clarify any of the concepts.

sysadmin devops linux git programming