How do I undo the most recent local commits in Git?

Git

If you have accidentally committed changes that you don't want to include in your repository, you can undo those commits using the git reset command. Here are the steps:

  1. Identify the commit(s) to undo:
    • Use git log or a similar command to find the SHA hash of the commit you want to undo. For example, if you want to undo the last commit, find the commit hash of the second-to-last commit.
  2. Run the reset command:
    • If you just want to undo the last commit, run:
      git reset HEAD^
      If you want to undo a specific commit, replace HEAD^ with the commit hash. For example:
      git reset <commit-hash>
  3. Handle the changes in your working directory:
    • If you just want to remove the changes from the last commit but keep them in your working directory, use the --soft option:
      git reset --soft HEAD^
    • If you also want to remove the changes from the last commit and remove them from your working directory, use the --hard option:
      git reset --hard HEAD^
  4. Verify the changes:
    • Run git status to see the changes in your working directory. The changes that were part of the last commit should no longer be staged.
  5. (Optional) Amend the commit message:
    • If you want to change the commit message of the commit(s) you just reset, run:
      git commit --amend -m "<new-commit-message>"
      Replace <new-commit-message> with your desired commit message.
  6. Push the corrected changes:
    • If you haven't pushed your changes to a remote repository yet, you can push them now:
      git push origin <branch-name>
      Replace <branch-name> with the name of the branch you are working on.

Please be aware that using git reset can be a destructive operation, especially when used with the --hard option. Ensure you have any important changes backed up or stored elsewhere before proceeding.



Back to The Programmer Blog