Undo commit in git
In this post, I’m going to take a look at some common scenarios where you might want to “undo” a change you’ve made using Git.
Undo a “public” change
Scenario: You just ran
git push, sending your changes to GitHub, now you realize there’s a problem with one of those commits. You’d like to undo that commit
git revert <SHA>
You can now
git push the new “inverse” commit to undo your mistaken commit.
Fix the last commit message
Scenario: You just typo’d the last commit message, you did
git commit -m "Fixes bug #42"but before
git pushyou realized that really should say “Fixes bug #45”.
git commit --amend or
git commit --amend -m "Fixes bug #45"
git commit --amend will update and replace the most recent commit with a new commit
Once more, with branching
Scenario: You made some commits, then realized you were checked out on
master. You wish you could make those commits on a feature branch instead.
git branch feature,
git reset --hard origin/master, and
git checkout feature
git branch feature creates a new branch called
feature pointing at your most recent commit, but leaves you checked out to
git reset --hard rewinds
master back to
origin/master, before any of your new commits. Don’t worry, though, they are still available on
git checkout switches to the new
feature branch, with all of your recent work intact.
Branch in time saves nine
Scenario: You started a new branch
masterwas pretty far behind
origin/master. Now that
masterbranch is in sync with
origin/master, you wish commits on
featurewere starting now, instead of being so far behind.
git rebase master
git rebase master does a couple of things:
- First it locates the common ancestor between your currently-checked-out branch and
- Then it resets the currently-checked-out branch to that ancestor, holding all later commits in a temporary holding area.
- Then it advances the currently-checked-out-branch to the end of
masterand replays the commits from the holding area after
master‘s last commit.
Entered Wrong Origin
Scenario:The error `fatal: remote origin already exists` is caused when you attempt to create a link to a remote repository called “origin” when a remote link with that name is already configured.
git remote set-url https://github.com/your/repository
The solution updates the URL of the remote repository with the name “origin” to the URL of the remote repository you want to add, instead of trying to create a new remote repository with that name.
Scenario:Occasionally, you can get into a situation where you make a merge, before realizing there’s an issue with it. When this happens, you’ll need a way to get your main branch back to its previous state.
git merge --abort
git merge --abort will abort the merge process and try to reconstruct the pre-merge state.