I accidentally committed the wrong files to Git, but didn’t push the commit to the server yet.
How can I undo those commits from the local repository?
There are two steps involved:
- Remove commits locally
- Force push the git forcefully
How do I undo the most recent local commits in Git?
Run command in the terminal to reset recent commit
git reset HEAD~
git reset HEAD~n
(to reset last n commits)
This will undo your commits but still, your changes will be there in files. It means it’s a soft reset that preserves changes.
How to undo the most recent local commits in Git with discarding changes?
Run command in the terminal to hard reset recent commit. It will discard local commits along with your changes in the files.
git reset --hard HEAD~
How do I undo the most recent remote commits in Git?
* If you accidentally committed the wrong code in a git repository and pushed it to git remote, don’t worry, you can still undo it by removing the commit(s) using the command:
git reset --hard HEAD~n
(where n is the number of commits you want to remove. This will remove commits and discard changes as well.)
HEAD is now at 62a271561 Commit message
* Second step would be a force pushing git repository to the remote repository. Make sure you’re on the correct branch (git status) and force push to remote using command:
git push --force