Undoing Changes in Git
For me, one of the most confusing git related topics was about git reset, revert, cherry-pick or even amend commands! It was really hard to grasp when to use which and why, so this guide will be all about that.
Linas KapoΔius
Solutions Architect at Corgineering.com
Reset
Moves the pointer (HEAD/current state) back to an earlier commit, undoing changes made after that point. It can also update your working files and the list of staged changes, depending on how you use it.
when to use:
- Youβre working locally and want to clean up your commit history before pushing.
- To undo commits that haven't been shared with others yet.
git reset [--soft | --mixed | --hard] <commit>
--ππππ: Resets HEAD to the specified commit but keeps your staged changes.
--πππππ (default): Resets HEAD and unstages changes, but leaves the working directory intact.
--ππππ : Everything is wiped, including staged and working directory changes. Use with caution!
Revert
Creates a new commit that undoes the effects of a previous commit, preserving the history of changes.
When to use:
- You need to undo a commit but have already pushed it to a shared branch.
- You want to preserve the integrity of your commit history in a team setting.
git revert <commit>
π‘ Pro Tip It is possible to revert multiple commits by specifying range:
git revert <start-commit >..< end-commit >
It is not enough? Do you need to revert multiple commits but skip some?That's where πͺπππππ-π·πππ helps.
Cherry-Pick
When to use:
- You want to selectively apply multiple commits from one branch to another without bringing in all the other changes from that branch.
- Great for bringing over bug fixes or small features from other branches without disrupting your current work.
git cherry - pick <commit-hash1> <commit-hash2> <commit-hash3>
Amend
Modifies the most recent commit, either by changing the commit message or including additional changes.
- To fix a typo or improve a commit message.
- You forgot to add a file and want to include it in the previous commit.
- Even to change commit author user name for specific commit.
git commit --amend
π‘ Pro Tip
After amending, use git push --force-with-lease instead of git push --force to safely force-push amended commits. It avoids overwriting commits that others might have made in the meantime.
This article is part of our Best Practices series. Check out our other articles.