Git by Example: Fast-Forward Merge
Understand the simplest type of merge in Git. A fast-forward merge happens when the target branch has not diverged from the source branch, allowing Git to simply move the pointer forward.
Code
# 1. Create a feature branch and add a commit
git switch -c feature-fast
echo "New feature" > feature.txt
git add feature.txt
git commit -m "Add feature.txt"
# 2. Switch back to main
git switch main
# 3. Merge the feature branch
git merge feature-fast
# Output:
# Updating 1a2b3c...4d5e6f
# Fast-forward
# feature.txt | 1 +
# 1 file changed, 1 insertion(+)
# create mode 100644 feature.txt
# 4. Verify the linear history
git log --oneline --graph --all
# Output:
# * 4d5e6f (HEAD -> main, feature-fast) Add feature.txt
# * 1a2b3c Initial commitExplanation
A fast-forward merge is the most efficient way Git integrates changes. It occurs specifically when the branch you are merging into (e.g., main) has not received any new commits since the feature branch was created. In this scenario, the history is strictly linear: the feature branch contains all the history of the main branch plus some new commits.
Because there is no divergent history to reconcile, Git does not need to create a new "merge commit". Instead, it simply picks up the label for the current branch (HEAD) and moves it forward to point to the same commit as the feature branch. This results in a completely straight line of history, as if the changes were made directly on the main branch. This keeps the project history clean and easy to follow.
However, you can force Git to create a merge commit even when a fast-forward is possible by using the --no-ff flag. This is sometimes useful if you want to preserve the historical information that a feature branch existed and was merged at a specific point in time, grouping those related commits together under a parent merge commit.
- Occurs when there is no divergent history
- Git simply moves the branch pointer forward
- No new merge commit is created by default
- Results in a linear project history

