Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git - discard previous commit, force push to remote

Tags:

git

commit

I will explain my situation first:

I had one file script in my newly created repository.

Then I did:

git add script
git commit -m 'initial commit'

git push -u origin master

..but then I realized I want comment-stripped version of my script file, so I did:

-- removed comments from my script using sed

git rm script
git add script-no-comments

which git recognized as file being renamed, which is ok.

,then:

git commit -am 'comments removed'

git push origin master

So now I have locally and on remote, two commits, first being file with comments, and another one without.

My question is: how can I now remove that first commit locally, keeping my last version with no comments, and then I suppose I could do force-push to remote thus overwriting commits there. I am not concerned in commit sha changes, as no one will pull but me?

Also would that remove that comment version for good, because I wouldn't like it to be recoverable?

like image 256
branquito Avatar asked Oct 20 '25 04:10

branquito


2 Answers

You can't "remove" the first commit, but you can just squash the two commits you've made into a single commit.

You can accomplish this with a git rebase -i HEAD~2, but I personally find this process easier:

Move you branch pointer back to the first commit:

git reset --hard HEAD~

Stage the changes from the previous commit:

git merge --squash HEAD@{1}

Commit your changes, amending them into a single commit.

git commit --amend

Force-push your new single commit to the server:

git push -f
like image 134
meagar Avatar answered Oct 22 '25 17:10

meagar


You could do an interactive rebase, squashing the two commits:

git rebase -i HEAD~2

Follow the instructions in the editor where you can also change the commit message.

The original commits still exist (but aren't reachable), you can remove them by garbage collection:

git gc
like image 22
Deve Avatar answered Oct 22 '25 18:10

Deve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!