Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use 'git rebase -i' to rebase all changes in a branch?

Tags:

git

Here's an example:

>git status # On branch master nothing to commit (working directory clean) >git checkout -b test-branch >vi test.c >git add test.c >git commit -m "modified test.c" >vi README >git add README >git commit -m "modified README" 

Now I want to do a 'git rebase -i' that will let me rebase all commits for this branch. Is there something like 'git rebase -i HEAD~MASTER' or similar. I figure I could do 'git rebase -i HEAD~2', but I really don't want to have to count how many commits have been made. I could also do 'git rebase -i sha1' but I don't want to comb through git log to find the first commit sha1. Any ideas?

like image 571
semmons99 Avatar asked Dec 12 '08 19:12

semmons99


People also ask

Can you rebase with changes?

Incorporating Upstream Changes Into a Feature Keep in mind that it's perfectly legal to rebase onto a remote branch instead of main . This can happen when collaborating on the same feature with another developer and you need to incorporate their changes into your repository.

What is rebase current changes onto branch?

Basically, what rebase does is rewind the current branch until it's at the point where it diverged from the target branch. Then, it takes the new commits of the current branch and applies them, one at a time, to the head of the target branch.


2 Answers

Ok, I'm asuming the branch is called "feature" and it was branched from "master".

There's this little git command called merge-base. It takes two commits and gives you the first common ancestor of both of those. So...

git merge-base feature master 

...will give you the first common ancestor of those two commits. Guess what happens when you pass that commit to git rebase -i, like...

git rebase -i `git merge-base feature master` 

Interactive rebase from the first common ancestor of both master and feature branch. Profit! ;)

like image 161
DanNetwalker Avatar answered Oct 15 '22 06:10

DanNetwalker


The issue with all provided solutions is, they do not allow you to rebase from the very first commit. If the first commit hash is XYZ and you do:

git rebase -i XYZ 

You only rebase starting from the 2nd commit.

If you want to rebase from the first commit you do:

git rebase -i --root 
like image 43
Joost den Boer Avatar answered Oct 15 '22 05:10

Joost den Boer