How to Use Git Reset for the Last Commit

Sometimes, you may find it necessary to roll back to a previous Git commit—perhaps due to premature commits, erroneous file inclusions, or the need for further modifications. The git reset command is your go-to solution for navigating this terrain, offering a straightforward way to correct course. It basically gives you more control over your project’s version history. This post shows you how to use this command.

How to use git reset to previous commit?

git reset provides the capability to rewind your project's history to a particular commit, offering a lifeline to revert unintended changes. This command comes in three flavors: soft, mixed, and hard, each serving different needs in terms of how they affect your working directory and staging area.

Soft reset

Opt for a soft reset when you wish to keep all your work but simply discard the last commit. This action moves the HEAD to a specified commit without altering your working directory or staging area.

git reset --soft HEAD~1

Executing this command undoes the last commit and keeps your changes staged, allowing you to recommit them after making any necessary tweaks.

Mixed reset

A mixed reset not only repositions the HEAD to a previous commit but also resets the staging area to match it, leaving your working directory changes intact but unstaged.

git reset HEAD~1

By default, git reset operates in mixed mode. This approach is ideal for when you aim to undo the last commit and examine your changes afresh before deciding on the next steps.

Hard reset

When you need to completely revert to a previous state, including discarding all changes in your staging area and working directory, a hard reset is the way to go.

git reset --hard HEAD~1

Approach this option with caution, as it wipes out all uncommitted changes, risking data loss if those changes are not saved elsewhere.

Deciding on the reset method

  • Use a soft reset to keep your work intact while redoing the commit.
  • Choose a mixed reset for an opportunity to review and adjust changes before committing again.
  • Reserve a hard reset for scenarios where reverting all recent changes and returning to a previous commit is absolutely necessary.

It's crucial to remember that altering shared history with git reset to previous commit can cause disruptions, especially if teammates have based their work on those commits. In collaborative environments, git revert offers a safer alternative, creating a new commit that negates previous changes without rewriting history, thus maintaining harmony within your project's development workflow.

Invite only

We're building the next generation of data visualization.