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 <commit-hash> # Reverts a specific commit
When to use each?
-
Use
reset
when working locally and want to completely remove a commit. -
Use
revert
if 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 stashes
When 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 main
When 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 commits
Inside 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.
Top comments (0)