Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 78 ยท Troubleshooting and Recipes

Fixing Common Git Mistakes

Fix the Git mistakes everyone makes: wrong branch, bad message, forgotten file, leaked secret, accidental merge, early push, detached HEAD and lost commits, with runnable repros.

Everyone makes Git mistakes: you commit on the wrong branch, misspell a message, merge too early or delete something you needed. The good news is that Git almost never destroys committed work. Most "disasters" are a pointer in the wrong place, and the fix is to move the pointer back. Understanding that turns panic into a routine.

This lesson is a field guide. Each section shows one common mistake, reproduces it in a throwaway repository, and applies the fix, so you can see the before and after. Use it as a reference: find your situation, read the fix, and understand why it works. Underneath all the fixes are only a few ideas, which you can learn in Undoing Changes, Reset in Depth, Revert and The Reflog.

First aid before any fix. Run git status and git log --oneline --graph --all -10 to see where you are. If you are unsure, make a safety copy of the current state with git branch backup (a branch is just a label, it costs nothing). A branch pins every commit it points to, so whatever you try next cannot lose that work.

1. I committed on the wrong branch

You meant to work on a feature branch, but you were still on main when you committed. The commit is not lost; it just has the wrong branch name attached. The fix: create the right branch at the current commit, then move main back.

Bash Move a commit to the right branch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git branch feature-x adds a second label to the commit. git reset --hard HEAD~1 moves main one commit back (and resets the working tree to match, which is safe here because the work is saved in feature-x). After that, main points at Base and feature-x carries the commit.

If you have already pushed the wrong commit to a shared main, do not reset; use git revert instead (see section 6).

If the commits were uncommitted changes, it is even simpler: git switch -c feature-x carries your uncommitted changes to the new branch.

2. I wrote a bad commit message

If it is the last commit and you have not pushed it, git commit --amend replaces it:

Bash Fix the last commit message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The hash changed, because the message is part of what a commit hash is computed from. Amending creates a new commit and moves the branch to it. That is why you must not amend commits that others already have. For older commits use git rebase -i and mark the commit reword (see Interactive Rebase).

3. I forgot to add a file

Same tool: stage the forgotten file and amend, keeping the message with --no-edit.

Bash Add a forgotten file to the last commit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The same trick works to remove a file you committed by mistake: git rm --cached file and git commit --amend --no-edit. If you want the file ignored from now on, add it to .gitignore (see Ignoring Files).

4. I committed a secret

Passwords, API keys and tokens in a repository are a security incident, not just a mistake. Two rules come first:

  1. Rotate the secret immediately. Assume it is compromised the moment it was pushed anywhere, even to a private repository. Removing it from history is cleanup; rotating is the fix.
  2. Then remove it from history so it does not keep spreading through clones.

If the secret is in your last, unpushed commit, amending is enough. If it is buried deeper, you need to rewrite history. Git ships git filter-branch (slow, deprecated but present everywhere); the separate git filter-repo tool is the modern choice but is not installed in the sandbox, so we use the built-in command here.

Bash Remove a secret file from the whole history

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git log -S ("pickaxe") finds commits that add or remove a string, so it proves the secret was in history and later proves it is gone. filter-branch rewrote the history without .env, so every hash from the Add config commit onward changed; --prune-empty dropped that commit completely because it contained nothing else, leaving three commits. The first search right after the rewrite still finds the secret, because filter-branch keeps a backup under refs/original. Three cleanup commands remove Git's safety copies: that backup, the reflog and unreachable objects. Only then does the second search come back empty. Without them, the old commits still sit in .git.

Rewriting history changes every later commit hash. Everyone with a clone must re-clone or reset to the new history, and anything already pushed must be force-pushed. Hosting platforms may also keep cached views of old commits (pull request refs, forks), so contact their support for sensitive leaks. This is why rotating the secret matters more than cleaning the history.

5. I merged by accident

You ran git merge on the wrong branch, or too early. If you have not pushed, the merge is only a commit on your branch, and ORIG_HEAD remembers where the branch was before the merge.

Bash Undo a local merge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Git sets ORIG_HEAD whenever a command makes a big jump (merge, rebase, reset, pull). Resetting to it puts main back before the merge, and the working tree matches. The experiment branch is untouched. If ORIG_HEAD was overwritten by a later command, use the reflog (section 8).

A merge that has started but conflicts can simply be abandoned with git merge --abort.

6. I pushed too early (or pushed a bad commit)

Once a commit is pushed to a shared branch, other people may have built on it. There are two ways out, and the choice depends on who has it.

The safe way for shared branches: revert. git revert adds a new commit that undoes an old one, so history only grows and nobody has to repair their clones.

Bash Undo a pushed commit with revert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The revert commit contains the opposite of the bad commit. The bad commit stays in the history, which is exactly why teammates' clones keep working. For a merge commit use git revert -m 1 <merge> (mainline parent 1), and read Revert first, because re-merging that branch later needs extra care.

The rewrite way for your own branch: reset and force-push with a lease. Only if nobody else has your commits (a private feature branch):

Terminal
git reset --hard HEAD~1
git push --force-with-lease origin my-feature

(Read-only: shown for the commands; the example above already used a local remote for the safe route.) --force-with-lease refuses to overwrite commits you have not seen. Never force-push to main or any shared branch.

7. I am in "detached HEAD" and made commits

Checking out a tag or a commit hash puts you in detached HEAD: HEAD points straight at a commit instead of a branch. You may even commit there, but when you switch away, nothing refers to those commits and they become candidates for garbage collection. The fix: give them a branch before you leave, or find them afterward in the reflog.

Bash Rescue commits made in detached HEAD

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

When you switch away, Git prints a warning that you are leaving one commit behind and shows its hash plus the command to save it (git branch <name> <hash>). In the reflog, HEAD@{1} is "where HEAD was before the last move", which is the hotfix commit. Creating a branch there makes the commit permanent again. The best habit: if you want to commit at an old point, start with git switch -c new-branch v1.

8. I lost commits (reset --hard, deleted a branch, bad rebase)

The reflog records every position HEAD and each branch had in your local repository, for about 90 days by default (30 for unreachable entries). Almost everything you "lost" is still there.

Bash Recover after reset --hard and a deleted branch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

For reset --hard, the entry HEAD@{1} is the commit before the reset, so git reset --hard 'HEAD@{1}' undoes it. For the deleted branch, git branch -D prints the commit it pointed to (was ...); that hash is all you need for git branch topic <hash>. The reflog entry for the commit message (commit: Topic work) lets you find it later. Quote 'HEAD@{1}' so the shell does not treat the braces specially.

The reflog only covers committed work. git reset --hard or git checkout -- file destroys uncommitted changes for good, and git clean -fd deletes untracked files, with no reflog to save you. Run git clean -n (dry run) first, and commit or stash before experimenting. See Stashing.

9. Quick lookup table

Situation Fix
Wrong branch, not pushed git branch right-name, then git reset --hard HEAD~N on the wrong one
Bad message on last commit git commit --amend -m "..."
Forgot a file git add file && git commit --amend --no-edit
Staged the wrong file git restore --staged file
Edited the wrong file, want it back git restore file (destroys uncommitted edits)
Undo last commit, keep changes git reset --soft HEAD~1
Undo last commit, drop changes git reset --hard HEAD~1
Undo a commit that is pushed git revert <commit>
Accidental local merge git reset --hard ORIG_HEAD
Merge with conflicts, want out git merge --abort
Detached HEAD with commits git switch -c new-branch
Lost commit or branch git reflog, then git branch name <hash>
Secret committed Rotate it, then rewrite history

Habits that prevent most of these

  • Run git status before every commit and git diff --staged to see exactly what you commit.
  • Commit often in small steps; each commit is a savepoint you can return to.
  • Create a branch before risky operations (git branch backup).
  • Prefer --force-with-lease to --force, and never force-push shared branches.
  • Prefer git switch and git restore over the older, overloaded git checkout.
  • Add .gitignore rules for .env, build output and editor files early (see Ignoring Files).
  • Install a pre-commit hook that scans for secrets (see Git Hooks).

Check your understanding

Quick check ยท 6 questions

of 6 answered You scored / 6 ยท perfect!

  1. 1. You committed on main by mistake and have not pushed. What is the simplest fix to move the commit to a new branch?

    A new branch pins the commit, so moving main back with reset loses nothing. Revert would add another commit instead of moving this one.
  2. 2. Why should you use git revert instead of reset for a commit that is already pushed to a shared branch?

    Revert only adds history. Resetting a shared branch would make everyone's local branch diverge from the rewritten one.
  3. 3. You accidentally ran git reset --hard HEAD~3 and lost three commits. What lets you get them back?

    The reflog records where HEAD was. The commits are unreachable but still exist until garbage collection, so you can move back to them.
  4. 4. You pushed an API key in a commit. What is the most important first step?

    Once published, a key must be treated as compromised. Rotation fixes the risk; history cleanup only reduces further spreading.
  5. 5. What does git commit --amend --no-edit do?

    Amend builds a replacement commit from the staged content; --no-edit keeps the old message. The hash changes.
  6. 6. Which of these can the reflog NOT bring back?

    The reflog tracks committed history positions. Changes that were never committed or stashed are not recorded.

Summary

  • Almost every Git mistake is a pointer in the wrong place; commits themselves rarely vanish, and branches and the reflog are your safety net.
  • Wrong branch: create a branch at the commit, then reset --hard the wrong one back. Bad message or forgotten file: git commit --amend.
  • Pushed shared commits are undone with git revert; rewrite history only on private branches, with --force-with-lease.
  • Secrets: rotate first, then remove from history (filter-branch or filter-repo) and clean up refs, reflog and objects.
  • ORIG_HEAD and HEAD@{n} from the reflog let you undo merges, resets and rebases. Save detached-HEAD work with git switch -c.
  • Uncommitted work is not recoverable: commit or stash before risky commands, and dry-run git clean -n.

Next: Git Recipes and One-Liners