git – discard previous commit, force push to remote

I will explain my situation first:

I had one file script in my newly created repository.

  • Managing files through Git that will never be committed
  • How to configure Git post commit hook
  • Git: change HEAD commit's message without touching the index
  • GIT: efficient way to prevent commiting non-functional changes?
  • How can I create a sibling branch that includes all the commits from another branch into one node?
  • How to get what changes were made in what files as part of git commit?
  • 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?

  • Can I use Git's ignore processing outside of Git?
  • Git work flow with an inexperienced member
  • How do you uninstall deleted files installed by git clone command?
  • How to view git changes if and only if they are not due to only white characters?
  • "fatal: strange pathname '-im/somerepo.git' blocked
  • Is there any Git web interfaces for locally hosted git projects?
  • 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.