The command git rebase
can be used to make various history adjustments, from rewriting the commit tree (and by doing that rewriting the history) to even pushing commits forward as if the branch were created in the future.
In this pro tip I will show you how to use git rebase
to update a branch.
Creating a example history
Suppose you have a project and you were working on a task on the branch task-2
, meanwhile someone else was working on the branch task-1
that was merged into main
and thus making the branch main
more up-to-date as shown in the drawing below:
Similarly, the history graph should look like the image below:
Knowing that main
is more up-to-date than your branch task-2
and following the good practice of always working with the most up-to-date project, you decide it’s time to update your working branch, which has the current history looking like this:
Updating the current branch
There are a few ways to update the current branch, one of them is using git merge
and merging the most updated branch, in this case main
, into the branch you want to update in this case task-2
. The other way is using the rebase that I’m going to show you now.
There are two ways of using rebase to make this update, let’s see the first one which is being on the branch you want to update , so you need to go to the branch to be updated, in this case task-2
and use rebase indicating the branch that is the source of changes:
git checkout task-2
git rebase main
By running these commands you will see in your terminal the message saying that the update was done successfully “Successfully rebased and updated refs/heads/task-2.” as you can see in the following image:
The second way is independent of the current branch , this format is a shortcut for the two previous commands, just use rebase, pass the source branch of the changes followed by the target branch:
git rebase main task-2
This command should also show the same message as the previous image. Regardless of the way you choose to use rebase, your history should look something like the drawing below:
And the history graph should look like this:
Wrapping up
Wrapping up, we have an important thing to point out now that our branch is updated: the rebase will only happen without interruptions, as shown in this pro tip blog post, if there are no conflicts, otherwise the rebase will be suspended and the conflicts must be resolved before continuing.
ow you know how to update a branch using rebase, if you want more details about the command git rebase
, I recommend reading its documentation.
Below you can see the git study card that can help you remember the command git rebase
to update a branch:
Top comments (0)