Saeed
Saeed

Reputation: 159

delete a commit from git which is not the last commit

Suppose we have two branches, master and local_branch and I have some commits in my_branch. I push all of my commits to repository and we assume when I use:

git log --pretty=oneline

These lines will be showed to me:

c682f01 (origin/local_branch) add final changes.
1bad4de add some local changes 2.
ef7d35e add some local changes 1.
f719c75 temp commit!
f0dcf28 some local changes.
adc5be1 (origin/master, origin/HEAD, master) Add design decisions.
baf2ec8 Add some feature 1.
edd3e66 initial commit

Suppose that I want to delete a commit (temporary commit) from local_branch.

How can I do it without corrupting other commits?

Which is the best way? Can I do it with this instruction:

git rebase -i

Upvotes: 0

Views: 129

Answers (2)

unixia
unixia

Reputation: 4360

You could do git rebase -i f0dcf28. You should see something like the following in open up in your editor:

pick c682f01 (origin/local_branch) add final changes.
pick 1bad4de add some local changes 2.
pick ef7d35e add some local changes 1.
pick f719c75 temp commit!
pick f0dcf28 some local changes.

Edit the pick in front of f719c75 temp commit! and replace it with d, i.e.

pick c682f01 (origin/local_branch) add final changes.
pick 1bad4de add some local changes 2.
pick ef7d35e add some local changes 1.
d f719c75 temp commit!
pick f0dcf28 some local changes.

Save this in your editor and exit. Your commit should be dropped now. You'll need to force push after doing this action.

Upvotes: 2

David Albrecht
David Albrecht

Reputation: 674

I would reset my local Branch to f0dcf28, cherrypick ef7d35e - c682f01, commit them and then force push them over to the remote. (Many repos are setup that you cannot force push to branches or at least not to the master branch. In that case there is nothing you can really do about the temporary commit)

git reset --hard f0dcf28
git cherry-pick my_branch~2 my_branch
git push -f

(Please be careful with the forcepush - I haven`t really tested this: Forcepush will overwrite your remote branch!)

Upvotes: 2

Related Questions