Fixes
Common Git mistakes and how to fix them
Almost every Git mistake can be undone. Find your situation below, run the commands, and read the one-line explanation so you know what they did.
git revert over git reset. Rewriting shared history causes problems for everyone else.I committed to the wrong branch
Move the commit to a new branch, then remove it from the current one. Only do this if you haven't pushed.
git branch correct-branch # new branch keeps the commit
git reset --hard HEAD~1 # remove it from this branch
git switch correct-branchI want to undo my last commit but keep the code
A soft reset takes the commit away and leaves everything staged.
git reset --soft HEAD~1I need to undo a commit I already pushed
Don't reset shared history. Revert creates a new commit that cancels the old one.
git revert <commit-hash>
git pushI made a typo in my last commit message
Amend replaces the last commit's message. If you already pushed, you'll need to force-push, so avoid it on shared branches.
git commit --amend -m "Correct message"I forgot to add a file to my last commit
Stage the file and amend, keeping the same message.
git add forgotten-file.js
git commit --amend --no-editI lost commits after a reset or deleted a branch
The reflog remembers every position HEAD has been at. Find the hash and point a branch at it.
git reflog
git branch recovered <commit-hash>I want to throw away all my local changes
Restore tracked files, and clean untracked ones. Preview the clean first: it can't be undone.
git restore .
git clean -n # preview
git clean -fd # delete untracked filesI committed a file that should be ignored
Remove it from Git's tracking but keep it on disk, then add it to .gitignore.
git rm --cached .env
echo ".env" >> .gitignore
git commit -m "Stop tracking .env"Git won't let me push: "Updates were rejected"
The remote has commits you don't. Bring them in first, then push.
git pull --rebase
git pushI'm stuck in a merge conflict
Open the files Git lists, choose the right lines, then stage and continue. Or back out completely.
git status # see conflicted files
# edit files, remove <<<<<<< ======= >>>>>>> markers
git add .
git commit
git merge --abort # or give up and go back
Need a command that isn't here? Search the full Git commands list, or read the in-depth git reset guide.