Git – Squash Commits: Merge All Commits in Branch Into One

Each time you are working on a bug or a feature, you create a branch for it.

Usually, while working in such temporary branches, you make multiply commits without bothering a lot about commit messages and simply comment the changes with something like “work in progress” or just “WIP”.

Before merging such branch into master it is a good practice to squash all commits in one with a single commit message that describes the summary of the changes.

Below i will show you how to squash commits in Git before merging a branch into master.

Cool Tip: Made a typo? Don’t worry! The most resent commit message can be easily changed! Read more →

Squash and Merge Commits in Git

Run the following Git commands to squash all commits in a branch into one and merge this branch into master with a single commit message:

$ git checkout master
$ git merge --squash <branch_name>
$ git commit

If you are working with a remote Git repository, don’t forget to push your changes:

$ git push

Squash Commits in Git Branch

Alternatively you can squash all commits in a branch as follows:

$ git checkout <branch_name>
$ git reset --soft master
$ git add -A
$ git commit

In this case you may need to force the push of the branch to remote:

$ git push -f 

Otherwise you may get the next error:

error: failed to push some refs to ‘https://path/to/repo.git’
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: ‘git pull …’) before pushing again.
hint: See the ‘Note about fast-forwards’ in ‘git push –help’ for details.

Leave a Reply