0

I'm happy with my current code, but I have 2 commits that went in the wrong direction and I would like to delete them. They are in my local git (xcode source control), and have also been pushed to Github.

How do I delete those two older commmits from my Git history while preserving what I have now?

Thanks very much in advance!

SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34
Frances
  • 1
  • 1
  • The problem with rewriting history in Git (changing the IDs) is that you have to rewrite everything that happened after the commits you want to delete. Do you have many commits after the 2 you want to remove, and can you rewrite all of those commits? Typically if there are other branches that came off of the branch in question after the commits you want to remove, then you should rarely ever do this. – TTT Jan 16 '21 at 23:55
  • Check this answer: https://stackoverflow.com/questions/34519665/how-can-i-move-head-back-to-a-previous-location-detached-head-undo-commits/34519716#34519716 – CodeWizard Jan 17 '21 at 02:15

1 Answers1

1

Warning potentially dangerous commands ahead -- proceed carefully.

You can rebase and squash the commits locally, then push to the remote and use the --force option to overwrite the remote history (Note: for this to work, your GitHub repo must allow force pushing)

On your local repository, run:

git rebase -i HEAD~3

The above will allow you to mark the last two commits as fixes and swash them all into a single commit.

Then, if all looks good locally, you can run:

git push --force

The Git manual has a nice explanation of your options for rewriting history. You should definitely go read that before you go forward with this.

But you really, really shouldn't do this unless the commits contain sensitive information that you don't want on GitHub. And definitely, don't do this if the repo is public with multiple contributors.

It's usually not a big problem to have some commits in the history that were wrong.

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • If you notice during `git rebase` that you did something wrong with rebasing, you can use `git rebase --abort` to restore your repo to the state **before** you entered the `git rebase`-command. – SwissCodeMen Jan 16 '21 at 23:13
  • Thank you all very much. I didn't know it was risky. I might try it anyway because I have everything backed up, just to get the experience. Don't worry, i don't think anyone else is using my repository. – Frances Jan 18 '21 at 18:06