Fixing Common Git Problems: A Troubleshooting Guide
A problem-by-problem guide to the errors that stop people most often: rejected pushes, divergent branches, local changes in the way, commits on the wrong branch, detached HEAD, lock files, unrelated histories, lost work, authentication and dubious ownership, with exact messages and fixes.
kvi5hnuCode Sprout team member9 min readOn this page
Most Git problems fall into a small number of patterns, and Git's messages usually say what's wrong, if you know how to read them. This guide is organized by symptom: find the message or situation, read why it happens, and apply the fix. Each entry links to the article that explains the topic fully. Two rules apply throughout: read the whole message, including the hint: lines, and when in doubt, commit or stash before trying fixes, because committed work can almost always be recovered (article 26).
Pushing and pulling
"! [rejected] main -> main (fetch first)" or "(non-fast-forward)"
Someone pushed commits you don't have. Git refuses to push because it would discard them. Integrate their work first, then push:
git init -q --bare server.git
git clone -q server.git sam 2>/dev/null; cd sam
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
cd ..; git clone -q server.git ana; cd ana
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "Add ridge page"; git push -q
cd ../sam
echo "Forest loop" > forest.txt; git add .; git commit -q -m "Add forest page"
git push 2>&1 | grep -v "^hint"
echo "=== integrate, then push"
git pull -q --rebase
git push -q && echo "pushed"
git log --oneline
To /workspace/server.git
! [rejected] main -> main (fetch first)
error: failed to push some refs to '/workspace/server.git'
=== integrate, then push
pushed
11cebd2 Add forest page
74d065f Add ridge page
3fb02f2 Add lake page
Don't respond to a rejected push with --force: that deletes your teammate's commits from the server. Use git pull --rebase, or git pull --no-rebase to merge (article 19). Force push only your own branches, and with --force-with-lease (article 20).
"fatal: Need to specify how to reconcile divergent branches."
You and the remote both have new commits, and Git doesn't know whether to merge or rebase, because pull.rebase isn't set. Choose once:
git config --global pull.rebase true # rebase local commits onto the remote's
# or
git config --global pull.rebase false # merge
# or
git config --global pull.ff only # refuse unless it's a fast-forward
"fatal: The current branch topic has no upstream branch."
The branch has never been pushed, so git push doesn't know where to. Run git push -u origin topic once, or set git config --global push.autoSetupRemote true so plain git push sets it up (article 20).
"fatal: refusing to merge unrelated histories"
The two branches have no common commit, typically because a repository was created on the hosting service with a README, and separately on your machine with git init. If you really mean to combine them, add --allow-unrelated-histories once: git pull --no-rebase --allow-unrelated-histories origin main. Otherwise, check that you have the right remote.
Authentication failures
| Message | Likely cause | Fix (article 21) |
|---|---|---|
| "Authentication failed", "Invalid username or token" | password used instead of a token, or an expired token | create a personal access token, and clear the stored credential |
| "Permission denied (publickey)" | SSH key not loaded or not added to your account | ssh -T git@github.com to test, add the key, check ssh-add -l |
| "Repository not found" for a repository that exists | no access with the current credentials | check the account and its permissions, and the URL |
| "SSL certificate problem" | company proxy or missing CA certificate | configure http.sslCAInfo. Never disable verification permanently |
Local changes in the way
"Your local changes to the following files would be overwritten by checkout"
You're switching branches, or pulling, and uncommitted changes in a file would be lost, because the other branch changes it too:
git init -q trail-guide && cd trail-guide
echo "Lake loop: 5 km" > lake.txt; git add .; git commit -q -m "Add lake page"
git switch -q -c fix-distance
echo "Lake loop: 5.4 km" > lake.txt; git commit -q -am "Fix lake distance"
git switch -q main
echo "Lake loop: 5 km, flat" > lake.txt # uncommitted work on main
git switch fix-distance 2>&1 | head -3
echo "=== stash, switch, come back, restore"
git stash -q
git switch -q fix-distance; git switch -q main
git stash pop -q
git status --short; cat lake.txt
error: Your local changes to the following files would be overwritten by checkout:
lake.txt
Please commit your changes or stash them before you switch branches.
=== stash, switch, come back, restore
M lake.txt
Lake loop: 5 km, flat
Options: commit the work, git stash it and git stash pop later (article 27), or bring the changes along with git switch -m if they should apply to the other branch. git pull with pull.autostash or rebase.autoStash set stashes and restores automatically.
"error: pathspec 'x' did not match any file(s) known to git" or "invalid reference"
A typo, a file that isn't tracked yet (git add it first), a branch that exists only on the remote (git fetch first, then git switch <name>, which creates a tracking branch), or a path relative to the wrong folder. Check with git status, git branch -a and git ls-files.
Commits in the wrong place
I committed to main instead of a new branch
Move the commits to a branch, then put main back, before pushing:
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null; cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "Add ridge page"
echo "Ridge parking" >> ridge.txt; git commit -q -am "Describe ridge parking" # oops: both on main
git branch ridge-page # 1. a branch keeps the commits
git reset -q --hard origin/main # 2. main goes back to what the server has
git switch -q ridge-page
git log --oneline --decorate --graph --all
* 30903e0 (HEAD -> ridge-page) Describe ridge parking
* 74d065f Add ridge page
* 3fb02f2 (origin/main, main) Add lake page
If they were already pushed to main, use git revert on main instead (article 24). For a commit that belongs on a different existing branch, git cherry-pick it there, then remove it here (article 16).
I need to change the last commit
- Wrong message, or a forgotten file:
git commit --amend(article 6), before pushing. - Undo the last commit but keep its changes:
git reset --soft HEAD~1. - Older commits: interactive rebase (article 15).
"You are in 'detached HEAD' state"
You checked out a commit, tag or remote branch directly, so new commits aren't on any branch. To keep work done there, create a branch before leaving: git switch -c keep-this. If you've already switched away, find the commit in git reflog and create the branch from it (articles 24 and 26).
Merges, rebases and conflicts
| Situation | Fix |
|---|---|
| in the middle of a conflicted merge and want out | git merge --abort (article 13) |
| in the middle of a rebase and lost track | git status says where you are. git rebase --abort returns to the start |
| a rebase or merge finished, but the result is wrong | git reset --hard ORIG_HEAD, or find the old position in git reflog (article 26) |
| the same conflicts again and again | enable rerere (article 13) |
a merged branch must be undone on main | git revert -m 1 <merge> (article 25) |
Lost work
| What was lost | Where to look |
|---|---|
a commit after reset --hard, rebase or amend | git reflog, then git branch rescue <id> |
| a deleted branch | git reflog for its last commit (the deletion message also prints it) |
| a dropped stash | git fsck --unreachable | grep commit, then inspect and git stash apply <id> |
| staged but never committed changes | git fsck --lost-found finds dangling blobs |
| uncommitted, unstaged changes | not in Git. Check your editor's local history |
All covered in article 26. The lesson: commit or stash often, because Git can recover anything it has seen.
Repository problems
"fatal: Unable to create '.../.git/index.lock': File exists."
Another Git process is running, or one crashed and left its lock file. Check that no Git command, editor integration or GUI is running, then delete the stale lock: rm .git/index.lock.
"fatal: not a git repository (or any of the parent directories): .git"
You're not inside a repository: check pwd, cd into the project, or git init if it's new. In scripts, use git -C <path>.
"fatal: detected dubious ownership in repository"
The repository folder belongs to a different user than the one running Git, which is common with shared drives, containers and repositories created with sudo. Git refuses, for security, because a malicious repository's configuration could run commands. If you trust it, add it: git config --global --add safe.directory /path/to/repo, or fix the folder's ownership.
Line ending warnings, or every line shows as changed
A mix of CRLF and LF line endings, usually from different core.autocrlf settings. Add a .gitattributes with * text=auto, then normalize once with git add --renormalize . and commit (article 35).
The repository is slow or huge
Large files in history (article 43), too many files (article 44), or no maintenance: run git maintenance start, check git count-objects -vH, and look at git repo structure.
A troubleshooting routine
When something's wrong and the message isn't clear:
git status: which branch, what's staged, and whether a merge, rebase or cherry-pick is in progress.git log --oneline --graph --all -15: where branches andHEADpoint.git reflog -10: what just happened toHEAD.- Back up before experimenting:
git branch backup-before-fixcosts nothing. - Read the hints, and the command's help:
git help <command>. - For strange behaviour, see what Git does:
GIT_TRACE=1 git <command>, orGIT_TRACE_CURL=1for HTTPS problems.git config list --show-originshows which configuration applies.
What's current
git config list --show-originand--show-scopeshow where each setting comes from, which answers many "why does Git do this?" questions.push.autoSetupRemoteremoves the "no upstream branch" error for new branches.- Since Git 2.35.2, the dubious ownership check protects against repositories owned by other users.
safe.directoryis the supported way to trust one.
Common questions
Is git push --force ever the fix for a rejected push?
Only for a branch you alone use, after you've rewritten it deliberately, and even then --force-with-lease is safer. For a shared branch, never: pull and integrate instead.
I ran git reset --hard and lost uncommitted changes. Can Git get them back?
Changes that were staged at some point may survive as dangling blobs: try git fsck --lost-found. Changes that were never staged or committed aren't in Git at all. Check your editor's local history.
How do I start over with a clean copy of the branch from the server?
git fetch origin, then git reset --hard origin/main, and git clean -fd for untracked files. That discards all local changes and commits on the branch, so make a backup branch first if there's anything to keep.
Git keeps asking for my password. What's wrong? No credential helper is configured, or it stores an outdated token. Set one up, such as Git Credential Manager or the macOS keychain, and use a token or SSH key (article 21).
Summary
- Rejected push: fetch and integrate (
pull --rebaseor merge), then push. Never plain--forceon shared branches. - Divergent branches: set
pull.rebaseorpull.ffonce. No upstream:push -uorpush.autoSetupRemote. - Local changes in the way: commit, stash, or
switch -m. - Wrong branch: create a branch at the commits, reset the original, and revert if already pushed.
- Lost work is in the reflog, or in
fsckfor stashes and staged content. - Stale
index.lock: delete it once no Git process runs. Dubious ownership:safe.directory. Line endings:.gitattributesand--renormalize.
Practice questions
git push is rejected with "(fetch first)". A colleague suggests git push --force. What do you do instead, and why?
Answer
Run git pull --rebase (or git pull with merging), resolve any conflicts, then git push. The rejection means the server has commits you don't have, and a force push would delete them from the server, losing your colleague's work.
You made three commits on main that should have been on a feature branch, and haven't pushed. Fix it.
Answer
git branch feature-x # keep the commits on a new branch
git reset --hard origin/main # move main back to the server's version
git switch feature-x
Make sure there are no uncommitted changes first, because reset --hard discards them.
Every Git command fails with "Unable to create '.git/index.lock': File exists." What's happening, and how do you fix it?
Answer
Git creates index.lock while updating the index, so that two processes can't change it at once. A crashed or still-running Git process left it behind. Check that no Git process, editor integration or GUI client is running, then delete .git/index.lock.
Review quiz
Test yourself on Part 12 with the Git Part 12 review quiz.
Previous: Git Best Practices: Commits, Branches, Reviews and Repository Hygiene

More in Git Course
Quiz: Git Delicate Details
Twenty-five questions on Git's subtle corners: what commit -a and stash leave out, empty folders, ignore patterns and negation, HEAD~ versus HEAD^, ours and theirs in a rebase, tags that don't move or don't push, describe, merge reverts, diff exit codes, stash conflicts and more.
Quiz: Git Interview Questions
Thirty Git questions of the kind asked in developer interviews: Git versus GitHub, the staging area, merge versus rebase, fetch versus pull, reset, revert and restore, detached HEAD, conflicts, force pushing, stash, cherry-pick, reflog, bisect, submodules, LFS and how commits are identified.
Quiz: Git Course Final Exam (All Parts)
The final exam for the Git course: thirty questions across all twelve parts, from the three areas and staging through branching, remotes, undoing, history investigation, configuration, tags, larger projects, patches, rewriting, internals and troubleshooting.
Quiz: Professional Git Practice (Git Part 12)
Sixteen questions on migrating to Git from Subversion, TFVC and Mercurial, team best practices for commits, branches and reviews, repository hygiene, and diagnosing and fixing the most common Git errors, with explanations.
Discussion
Sign in to ask a question or share what you learned.