Walkthrough of a Simple Rebase
Learn about "git rebase" with the help of an example.
Rebase scenario#
Let’s walk through the scenario from the previous lesson with Git commands.
1 mkdir lgthw_rebase
2 cd lgthw_rebase
3 git init
4 echo A > file1
5 git add file1
6 git commit -am A
7 echo B >> file1
8 git commit -am B
9 echo C >> file1
10 git commit -am C
11 git checkout -b feature1
The -b
flag#
This is a shortcut that creates the branch and checks it out all at once. Using this means you don’t get into the situation where you can create a branch but forget to explicitly check it out before committing more changes.
12 echo D >> file1
13 git commit -am D
14 git checkout master
15 echo E >> file1
16 git commit -am E
17 echo F >> file1
18 git commit -am F
19 git log --all --decorate --graph
State: Before rebase#
You are now in this state:
Now go to the feature1
branch and rebase:
20 git checkout feature1
21 git rebase master
Read the output carefully and follow the instructions. It’s hard to follow, so don’t be concerned if you don’t get it the first time you try. Keep at it!
Stuck?
If you are struggling at this point, then you need to review this chapter on merging and conflicts.
Resolve conflicts#
The next command is there to indicate that you should resolve the conflicts mentioned.
22 vim file1
Note: Since changes you made after
vim
are unique to your own, you can either continue using the above terminal for all the following commands in this lesson or use the following terminals with ourvim
edit.
--continue
rebase session#
Now that you’ve resolved the conflicts, you can continue the rebase session:
23 git add file1
24 git rebase --continue
Applying: D
25 git log --all --decorate --graph
State: After rebase#
The state now looks like this:
Merging and Fast-Forwarding#
Now the changes are in one line you can merge the feature1
branch into the master
branch to move the feature1
branch pointer along. Here we return to the git merge
command you looked at earlier:
26 git checkout master
27 git merge feature1
28 git log --all --decorate --graph
And you end up in your desired state:
Note that merging and rebasing are separate topics, but you return to it here because it’s easiest to understand fast-forwarding in this context.
Fast-forwarding#
What’s interesting about the above is the output of the following command:
git merge feature1
Because the changes are in a line, there aren’t any new changes that need to be made. The master
branch pointer merely needs to be “fast-forwarded” to the same point as feature1
!
Naturally, the HEAD
pointer moves with the branch you’re on (master
).