1- Undoing Commits (reset vs. revert)
git reset - Undo commits and move the branch pointer
Git reset is used to undo commits. It comes in three types:
-
--soft→ Keeps changes in Staging (index). -
--mixed→ Keeps changes in Working Directory (default). -
--hard→ Deletes commits and changes permanently.
Example:
git reset --soft HEAD~1 # Undo last commit but keep changes staged
git reset --mixed HEAD~1 # Undo last commit and unstage changes
git reset --hard HEAD~1 # Undo commit and delete changes permanently! ⚠️
git revert - Undo a commit without deleting history
Unlike reset, revert creates a new commit that cancels the changes of a previous commit.
Example:
git revert HEAD # Reverts the last commit with a new commit
git revert # Reverts a specific commitWhen to use each?
-
Use
resetwhen working locally and want to completely remove a commit. -
Use
revertif the commit has already been pushed and you want to keep history clean.
2- Stashing - Saving Changes Temporarily
git stash is used to save uncommitted changes temporarily without committing them.
Example:
git stash # Save changes and get a clean working directory
git stash pop # Retrieve the latest stash and remove it
git stash apply # Retrieve the latest stash without removing it
git stash list # Show all saved stashes
git stash clear # Delete all stashesWhen to use stash?
- When working on a feature branch and need to switch to another branch without committing.
- When testing something quickly but don’t want to commit unfinished changes.
3- Rebasing - Merging Branches in a Linear Way
git rebase moves commits from one branch to another without creating extra merge commits.
Example:
git checkout feature-branch
git rebase main # Moves feature-branch commits on top of mainWhen to use rebase?
- To keep commit history clean and linear instead of multiple merge commits.
- To update a feature branch with the latest changes from
main.
4- Interactive Rebasing - Editing Commit History
git rebase -i allows you to edit, reorder, squash, or delete commits interactively.
Example:
git rebase -i HEAD~3 # Edit last 3 commitsInside the editor, you can:
- pick → Keep commit as is
- reword → Change commit message
- edit → Modify commit contents
- squash → Merge commits
- drop → Delete commit When to use interactive rebasing?
- To clean up messy commit history before pushing.
- To combine multiple small commits into one.