Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to overwrite commit with new one on git? [duplicate]

Tags:

git

github

So I'm working on a sensitive project with a group and all our sources are on Github. I recently pushed a commit and later realised there were lot of mistakes in my push. I've since fixed all those mistakes on my local copy and am about to push again. However is there any way I can push and overwrite my last commit? My reason being, I don't want the others to look up my initial commit and the changes it had...

Basically I want to overwrite the old commit with my new one.. so no information about the old commit remains for other group members to see.

Any help will be appreciated! Thank you.

NOTE: Just noticed that this question was marked as a duplicate. To clarify, my question is about overwriting a commit that has already been pushed. My question is NOT about changing an incorrect commit message.

like image 296
sparta93 Avatar asked Feb 21 '16 23:02

sparta93


People also ask

How do you add new changes to existing commit?

Use git commit --amend to change your latest log message. Use git commit --amend to make modifications to the most recent commit. Use git rebase to combine commits and modify history of a branch.

How do I amend a commit with the same message?

On the command line, navigate to the repository that contains the commit you want to amend. Type git commit --amend and press Enter. In your text editor, edit the commit message, and save the commit.

Does git push overwrite?

Warning: force pushing will overwrite the remote branch with the state of the branch that you're pushing. Make sure that this is what you really want to do before you use it, otherwise you may overwrite commits that you actually want to keep.


1 Answers

Usually, once something is out on Github (or a public repo), there's no way to make sure no one else has the bad commit.

If you simply want cleaner code history though, the way to do what you ask requires you to overwrite history both locally and on the remote project.

What you want is to either do a git commit --amend to modify your old commit if you've not already created a fresh commit with your changes.

If you've already created a fresh commit, you'll want to use git rebase -i to squash your commit on top of the old one.

After you've made this change locally, and verified your commit looks the way you want it to, you'll have to git push --force to overwrite history on the Github remote.

Here's a tutorial on how to re-write history in git, it explains both the approaches listed in this answer.

like image 70
ffledgling Avatar answered Oct 05 '22 14:10

ffledgling