Git Troubleshooting and Common Pitfalls
Even experienced Git users run into problems from time to time. This page covers common issues, error messages, and how to recover from mistakes.
Resolving Merge Conflicts
When two branches change the same part of a file, Git can’t merge automatically.
How to resolve:
- Git will mark the conflicted files. Open them and look for
<<<<<<<
,=======
, and>>>>>>>
. - Edit the file to keep the correct changes.
- Stage the resolved file:
git add <file>
- Complete the merge:
git commit
Undoing Commits
- Undo the last commit (keep changes staged):
git reset --soft HEAD~1
- Undo the last commit (keep changes unstaged):
git reset --mixed HEAD~1
- Undo the last commit (discard changes):
git reset --hard HEAD~1
- Revert a specific commit (safe for shared history):
git revert <commit-hash>
Recovering Lost Commits with Reflog
If you lose a branch or commit, use git reflog
to find its reference and recover it.
git reflog
git checkout <commit-hash>
Fixing Detached HEAD State
If you see “detached HEAD”, you’re not on a branch.
- To save your work:
git checkout -b my-new-branch
Dealing with Accidental Pushes
- Undo a pushed commit (if safe):
git revert <commit-hash> git push origin main
- Force push (dangerous, avoid on shared branches):
git push --force
Permission Errors
- Check your SSH keys:
ssh -T git@github.com
- Update remote URL to use SSH or HTTPS as needed.