Git — force & history surgery
Advanced Power tools. Easy to hurt shared branches.Amend last commit
bash
# change message only
git commit --amend -m "better message"
# add forgotten file into last commit
git add forgotten.txt
git commit --amend --no-editIf already pushed: need a force push (prefer lease):
bash
git push --force-with-leaseInteractive rebase (tidy before PR)
bash
git rebase -i origin/main
# or last 3 commits:
git rebase -i HEAD~3Common actions in the todo: pick, reword, squash, fixup, drop.
Force push safely
bash
# BAD on shared branches
git push --force
# BETTER — fails if remote moved
git push --force-with-leaseNever force-push main unless you own the repo and everyone agrees.
Recover with reflog
bash
git reflog
git switch -c recovery HEAD@{3}
# or reset current branch (destructive):
git reset --hard HEAD@{3}Undo a commit (keep changes)
bash
git reset --soft HEAD~1 # uncommit, keep staged
git reset HEAD~1 # uncommit, keep unstaged (mixed)Revert a public commit (safe for shared history)
bash
git revert <sha>
git pushCherry-pick
bash
git cherry-pick <sha>
git cherry-pick -n <sha> # apply without commit