git, squashing commits on the fly

I have a local git repo, one remote repo.
I made 5 commits to local repo since last pull from remote.

Now I need to push to remote. And I need to squash my last 5 commits.

  • How to make git merge handle uncommitted changes to my working tree?
  • JGit sets git: URI instead of https: for remote on CircleCI
  • git - merge difference of branches
  • What's the Git approach to publish a patch queue?
  • Keeping two Git branches different by one file
  • do a git cherry-pick in multiple branches
  • I can do it by git rebase -i HEAD~5

    But it’s not good. I don’t want to change anything in my local repo. I want to push one squashed commit to remote and leave 5 unchanged commits in my local repo.

    Any ideas?

    what about if I have my local repo with 5 commits. and I need to create new remote repo to share my code with others. How to squash commits for this new repo?

  • Git add all subdirectories
  • How do I react to new tags in git hooks?
  • Query on setting up a pre-receive hook in git
  • Git Pull Doesn't Do A Git Fetch
  • How I undo some changes in my workspace and get back to my last commit?
  • git: show all files changed between two commits
  • 2 Solutions collect form web for “git, squashing commits on the fly”

    Slight variation from Titas’s answer, without touching your master branch, and squashing on a new branch (that you would push to your new repo)

     git remote add newrepo url://of/your/new/repo
     git checkout -b newbranch master
     git merge --squash master 
     git push -u newrepo newbranch:master

    But that would push the full history of master, +1 (squashed) commit, on your new repo.

    If you wanted a branch new history, with your repo as after the 5 new commits, it is easier to:

    • clone locally your repo,
    • remove the .git in that local clone,
    • git init. (ie, re-create a new local git repo from all the existing files),
    • add everything and do one commit,
    • add your remote (to your new remote repo),
    • and push that one commit of your new local repo.

    If you just want to keep your five commits for reference, maybe you should work in a branch with them.

    1. git branch new-branch master
    2. Do your commits. Since you have done this, just reset head of master:

      git reset --hard HEAD~5

    3. git merge --squash master new-branch
    4. git push

    You will end up with squashed commit on master and origin/master and 5 commits on new-branch.

    Git Baby is a git and github fan, let's start git clone.