Let’s say you had checkout code from a branch and working on some changes and you did some local commits. Later, you realized that some of those changes are messy and you wanted to discard them. This sneppet guides you on how to throw away the local commits from your Git branch.
Your branch is ahead of ‘origin/main’ by ‘x’ commits
After messy changes, when you run git status command, you found that your branch is ahead of ‘origin/main’ by ‘x’ commits and you wanted to discard or throw away all the local commits from your Git branch.
Throw away all local commits
Following is the git syntax to throw away all local commits from your branch:
git reset --hard origin/<branch-name>
For example, if your branch name is “main”, then the following is the git command your need to run to get rid of all local commits that are visible only to you.
git reset --hard origin/main
Please note, the above command not only throw away all local commits, it will also delete all your local files that you might have created.
If you just want to do undo only the commit action that you performed and leave everything else intact, then you need to run the following git command.
git reset --soft HEAD^
And, the following git command will throw away any uncommitted changes you have in your branch. And HEAD points to current commit. Therefore, please be cautious while using –hard flag with git reset command.
git reset --hard HEAD^
Hence, I would suggest you to use git status command to check if your local branch is clean before using the command.
Reset to specific commit hash
You can also use the following git command to reset to specific commit reference.
git reset --hard <commit-hash>
git reset --hard 6cee22e
Hope you find this sneppet helpful. Please comment if it helped 🙂
You’ll Also Like
- Undo git reset –hard HEAD^ and revert to previous commit ?
- How to connect to Github using SSH ?
- Git – How to compare files in two different branches
- Git not working with a proxy server – gnutls_handshake() failed
- npm ERR! enoent spawn git ENOENT
- GitHub unable to access HTTPS and SSL routines error
- Remove http and https proxy settings of npm and git ?
- Fix Nodejs Error: ENOENT: no such file or directory