Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: How to rebase and squash commits from branch to master?

Tags:

I'm trying to rebase and squash all my commits from current branch to master. Here is what I'm trying to do:

git checkout -b new-feature 

make a couple of commits, after it I was trying:

git rebase -i master 

in this case commits will remain in new-feature branch

git checkout master git rebase -i new-feature 

It gives me and edit window with noop message.

I know about command:

git merge --squash new-feature 

But I'm currently working on learning of rebase command.

like image 275
Viacheslav Kondratiuk Avatar asked Mar 31 '13 08:03

Viacheslav Kondratiuk


People also ask

How do I rebase a branch to a master?

To rebase, make sure you have all the commits you want in the rebase in your master branch. Check out the branch you want to rebase and type git rebase master (where master is the branch you want to rebase on).

How do I merge squash commits to master?

Squash merging is a merge option that allows you to condense the Git history of topic branches when you complete a pull request. Instead of each commit on the topic branch being added to the history of the default branch, a squash merge adds all the file changes to a single new commit on the default branch.

Should I squash commits when merging to master?

As a general rule, when merging a pull request from a feature branch with a messy commit history, you should squash your commits. There are exceptions, but in most cases, squashing results in a cleaner Git history that's easier for the team to read.


1 Answers

Lets go though the steps.

1 - We create a new feature branch

git checkout -b new-feature 

2 - Now you can add/remove and update whatever you want on your new branch

git add <new-file> git commit -am "Added new file" git rm <file-name> git commit -am "Removed a file" cat "add more stuff to file" >> <new-file> git commit -am "Updated files" 

3 - Next, pick and squash any commits down into one nice pretty commit message

git rebase -i master 

The key thing you need to remember here is to change the text that says "pick" to "squash" for all of the commits after the first commit. This will squash all of the commits down to your master branch.

4 - Select the master branch

git checkout master 

5 - Move the HEAD and the master branch to where new-feature is:

git rebase new-feature 

You can try all of the commands out in this visual tool: http://pcottle.github.io/learnGitBranching/

like image 125
Joe Avatar answered Oct 16 '22 13:10

Joe