How Do I Undo the Most Recent Local Commits in Git?

Better Stack Team
Updated on June 21, 2024

To undo the most recent local commits in Git, you have a few options depending on what you want to achieve. Here's how you can do it:

Undoing the commit but keeping changes:

If you want to keep the changes from the commits but undo the commit itself, you can use git reset with the --soft option:

 
git reset --soft HEAD~1

This command will move the HEAD pointer of your current branch to the parent of the current commit (HEAD~1), effectively "undoing" the commit but keeping your changes staged. You can then make further modifications and commit again.

Undoing the commit and discarding changes:

If you want to completely undo the commit and discard any changes made in those commits, you can use git reset with the --hard option:

 
git reset --hard HEAD~1

This command will reset both the HEAD pointer and the working directory to the state of the commit before the most recent one, effectively discarding any changes made in the commit.

Undoing and preserving changes:

If you want to undo the commit but keep the changes in your working directory (without staging them), you can use a combination of git reset and git stash:

 
git reset HEAD~1
git stash

The first command (git reset HEAD~1) will undo the commit and keep the changes in your working directory. The second command (git stash) will then stash those changes so that you can reapply them later if needed.

Note:

  • Be cautious when using git reset --hard as it will discard any changes made in the commit.
  • If the commits have already been pushed to a remote repository, it's generally not recommended to use git reset as it can cause issues for other collaborators. Instead, consider using git revert to create a new commit that undoes the changes introduced by the previous commit.
Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github