Back to Articles
Programming Feb 12, 2026 · 6 min read

Git Undo: The commands I wish I knew earlier

Daniel

Software Developer

It happens to everyone. You commit to master. You push API keys. You merge a broken branch. Here is how to fix it.

1. You committed too early

Forgot to add files? Commit message wrong?

git commit --amend  --amend to modify the last commit
git commit --amend --no-edit  -- keep the same message

2. You committed to the wrong branch

You meant to commit to feature/login but committed to main.

git reset --soft HEAD~1  -- undo last commit, keep changes staged
git stash  -- stash those changes
git checkout feature/login  -- switch to correct branch
git stash pop  -- apply changes
git commit -m "Add login feature"  -- commit correctly

3. You pushed secrets

Github tells you the commit contains secrets. Remove it:

git reset --hard HEAD~1  -- remove the commit completely
git push --force  -- force push (careful!)

4. You want to see what changed before undoing

git log --oneline -10  -- see recent commits
git show HEAD~3 --stat  -- see what was in commit 3 ago

5. You merged the wrong branch

This one is scary. You can undo a merge:

git reset --hard HEAD~1  -- go back to before merge
-- OR --
git revert -m 1 HEAD  -- create a new commit that undoes the merge

Prevention is Better

  • Always check git status before pushing
  • Use .gitignore - add env, node_modules, etc. before first commit
  • Protect main/master in GitHub settings