What is a fast-forward merge in Git?

Fast forward merge can be performed when there is a direct linear path from the source branch to the target branch. In fast-forward merge, git simply moves the source branch pointer to the target branch pointer without creating an extra merge commit.

Let us look at an example implementing fast-forward merge.

We have a master branch with 3 commits.

Next, we create a branch called feature branch. In git a branch is nothing but a pointer to a commit. At this point both feature and master are pointing to the same commit.

Now let us switch to the feature branch and do a couple of commits. Now we need to bring the changes to the master branch. There is a linear path from feature to master.

In order to merge the changes to the master branch, all git has to do is to change the pointer of master forward. This is what we call fast-forward merge.

Let us understand fast-forward merge through a real-world example.

Let us say we have a directory called MAIN_V1.0. The code in this directory is of version 1.0. We take a copy of this directory and call it as BUGFix_V1.0. Code in BUGFix_V1.0 is identical to the code in the MAIN directory. Now let’s say we made changes in the BugFix directory and made it to BUGFix_V2.0. Once we have completed the changes in bugfix, how do we bring the changes back to the MAIN folder?

Solution 01 − Copy all files from Bugfix to Main. This is not the best solution as copy operations may take long time if we have many files in the Bugfix version 2.0 folder. There should be a better way

Solution 02 − Since there is no additional change in the MAIN directory and everything in MAIN is essentially the first version of BUGFix directory, we can simply rename BUGFix to MAIN. From this point forward, we can say this is our new MAIN directory. The concept of fast forward merge in git is very similar to this solution.

So, if two branches have not diverged and there is a direct linear path from the target branch to the source branch, Git runs a fast forward merge.


$ git init
$ echo hello>hello.txt
$ git add .
$ git commit -m 'first'
$ echo hello>>hello.txt
$ git add .
$ git commit -m 'second'
$ echo hello>>hello.txt
$git commit -m 'third'
$ git add .
$ git commit -m 'third'
$git branch feature
$ git switch feature
$ echo world>>hello.txt
$ git add .
$ git commit -m 'world1'
$ echo world>>hello.txt
$ git add .
$ git commit -m 'world2'
$ git switch master
$ git merge feature
$ git merge feature


Updating 1c80cb1..571c901
hello.txt | 2 ++
1 file changed, 2 insertions(+)

Updated on: 30-Apr-2021

24K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started