How to Undo the Most Recent Local Commits in Git

The easiest way to undo the most recent local commits in Git is to “use the git reset command with the –hard option followed by the number of commits you want to undo.”

To undo the last commit, use this command:

git reset --hard HEAD~1
  1. git reset: This is the command used to reset the current HEAD to a specified state.
  2. –hard: This is an option that tells Git to reset the index and the working directory to match the desired commit. Any changes in the working directory and index since the specified commit will be discarded.
  3. HEAD~1: This is a shorthand notation in Git. HEAD represents the current commit, and ~1 moves one commit backward in history. So, HEAD~1 refers to the commit before the current one.

The command git reset –hard HEAD~1 is a powerful command that allows you to reset your current branch’s HEAD to the previous commit.

When you run this command, the most recent commit is “erased” from your branch’s history in your local repository.

However, if you had previously pushed this commit to a remote repository, the remote will still have this commit. If you wish to synchronize the remote with your local changes, you would need to force push, but be cautious: this can overwrite changes on the remote and disrupt the work of others if they have pulled the original commit.

To keep the changes made in the undone commits, you can “use the git reset command with the –soft option instead.” This will remove the commit from your local repository but keep the changes staged so you can commit them again.

git reset --soft HEAD~1

If you have pushed the commits to a remote repository, use the “git push with the –force” option to update the remote repository with the changes.

git push --force origin <branch-name>

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.