git rebase

With git rebase you can combine commits, remove commits from a branch, reorder commits, re-word commits, and more.

In addition to the basic rebase example below, you can also use git rebase to:

A strong use case for git rebase is to ensure that the changes you are working on are fast-forward from a remote branch that may have been modified by other engineers, etc. This isn’t everything that git rebase can do, but you may find that with a combination of the above techniques, you can usually achieve what you need.

Is `git rebase` dangerous?
You will probably see mention out there that “rebase is dangerous.” Please take those admonitions with a grain of salt. git rebase is no more dangerous than any other git command. If you look closely, the message is usually “git push --force is dangerous.” And you should with, few exceptions, never use git push --force. Instead, git push --force-with-lease is a much better option.

Basic Rebase Example

By default, git rebase with one argument will take the name of a rebase target, and attempt to apply each commit from your current branch to that target, one by one. This results in a state where you have all the commits from the target, and then your novel commits that didn’t exist in the target applied after them, in order.

Let’s imagine have a new feature to work on. You create a branch called me/feature, based on your mainline branch (main) and then you start working. And let’s say that, so far, you’ve created two commits, F and G, but you have more work to do.
git fetch --all
git checkout main
git reset --hard origin/main
git checkout -b me/feature

# ...start editing/committing
A few days later, you’re still working on your feature, but a new commit, B, has been added to main that doesn’t yet exist in your branch.
main
A
B
me/feature
A
F
G
What if you could rearrange the commits so that it was as if you had started with commit “B?” The polite and sanity-preserving thing to do is to keep up to date with the changes to the mainline branch you’ll eventually be integrating your work into. So rebase it “on top of” main.
git fetch --all
git checkout me/feature
git rebase origin/main
Now me/feature is exactly main with your latest feature commits applied on top. If you were to merge me/feature into main, it would by default be a “fast-forward” merge.
main
A
B
me/feature
A
B
F
G

How can you tell how two git branches differ?
If you want to see the difference in commits between two branches or commits, use git show-branch.
How come I haven't heard about this before? People always seem to use "git merge" instead
git rebase is right for many small teams, but may not be right for all teams. This is because it will require you to force push your changes to the remote. The good news is that, even with others using the same codebase, this new force-pushed commit should rebase very easily under whatever they in turn are working on.