Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a git commit between two commits

Tags:

git

github

I added some functionality in my project which took 4 git commits, now business is asking that the functionality is no more needed(After more than a month). So I need to remove those particular git commit(s) from my repo which now has 27 more commits after that.

like image 854
Niranjan Kumar Avatar asked Nov 13 '16 06:11

Niranjan Kumar


People also ask

How do I remove a commit between two commits?

To remove the last commit from git, you can simply run git reset --hard HEAD^ If you are removing multiple commits from the top, you can run git reset --hard HEAD~2 to remove the last two commits. You can increase the number to remove even more commits.

How do I remove a commit in the middle?

If the commit were not pushed to a remote server, you can use git rebase to modify the git history. It will show a list of commits. The first line should be the commit you want to delete. Remove that line from the file you edited, save and close.


1 Answers

There are four ways of doing so:

  • Clean way, reverting but keep in log the revert:

    git revert --strategy resolve <commit>
    
  • Harsh way, remove altogether only the last commit:

    git reset --soft "HEAD^"
    
  • Rebase (show the log of the last 5 commits and delete the lines you don't want, or reorder, or squash multiple commits in one, or do anything else you want, this is a very versatile tool):

    git rebase -i HEAD~5
    

And if a mistake is done:

git rebase --abort
  • Quick rebase: remove only a specific commit using its id:

    git rebase --onto commit-id^ commit-id
    
  • Alternatives: you could also try:

    git cherry-pick commit-id
    
  • Yet another alternative:

    git revert --no-commit
    
  • As a last resort, if you need full freedom of history editing (eg, because git don't allow you to edit what you want to), you can use this very fast open source application: reposurgeon.

Note: of course, all these changes are done locally, you should git push afterwards to apply the changes to the remote. And in case your repo doesn't want to remove the commit ("no fast-forward allowed", which happens when you want to remove a commit you already pushed), you can use git push -f to force push the changes.

Note2: if working on a branch and you need to force push, you should absolutely avoid git push --force because this may overwrite other branches (if you have done changes in them, even if your current checkout is on another branch). Prefer to always specify the remote branch when you force push: git push --force origin your_branch.

like image 72
mrid Avatar answered Sep 21 '22 14:09

mrid