git – discard previous commit, force push to remote

I will explain my situation first:

I had one file script in my newly created repository.

  • What is the difference between git commit and git commit-tree
  • How to remove all occurences of a file in index, from all git commits
  • How to find commits by a specific user in Git?
  • GIT Log or Commit Monitor
  • how do i find a list of files committed to a branch?
  • do a git pull to overwrite local changes
  • 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.


    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?

  • Sublime Text won't automatically change code, when I switched to different branch
  • Automatically add .gitignore and hooks on git init
  • How can I delete a commit to git
  • Git: how to make remote directory update when pushed to?
  • Git: multiple subtrees/submodules in one folder?
  • Git filter branch from HEAD
  • 2 Solutions collect form web for “git – discard previous commit, force push to remote”

    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

    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
    Git Baby is a git and github fan, let's start git clone.