Git Merge
Last updated
git merge brings the commits from another branch into your current one. When the current branch hasn't diverged, Git fast-forwards - just moving the pointer forward. When both branches have new commits, Git creates a merge commit that ties the two histories together. Unlike rebase, merge preserves the exact history of both branches.
Try these in the terminal playground - a real shell in your browser, nothing to install.
Syntax
| Command | What it does |
|---|---|
git merge feature | Merge feature into the current branch |
git merge --no-ff feature | Always create a merge commit |
git merge --ff-only feature | Only merge if it can fast-forward |
git merge --squash feature | Combine the branch's commits into one |
git merge --abort | Cancel a conflicted merge |
Fast-forward vs merge commit
| Scenario | Fast-forward | Merge commit (--no-ff) |
|---|---|---|
| Creates a new commit | No | Yes |
| Keeps a record of the branch | No | Yes |
| Happens when | Current branch hasn't diverged | Both branches have new commits |
Resolving a merge conflict
When both branches changed the same lines, Git pauses.
| Step | Command | Result |
|---|---|---|
| 1 | Edit the conflicted files | Pick the correct lines, remove the markers |
| 2 | git add <file> | Mark the conflict resolved |
| 3 | git commit | Complete the merge |
Git merge FAQ
How do I merge a branch into another in Git?
Switch to the branch you want to merge into (e.g.
git switch main), then run git merge feature. Git combines the commits from feature into main, either by fast-forwarding or by creating a merge commit if both branches have diverged.What's the difference between a fast-forward and a merge commit?
A fast-forward happens when your current branch hasn't moved since the other branch split off - Git just slides the pointer forward, no new commit. A merge commit is created when both branches have new commits, tying their histories together. Use
--no-ff to always create a merge commit, or --ff-only to require a fast-forward.How do I resolve a merge conflict?
When a merge conflicts, Git marks the clashing sections in the affected files with
<<<<<<<, =======, and >>>>>>> markers. Edit each file to keep the correct content and remove the markers, then git add the resolved files and git commit to finish the merge.How do I undo or abort a merge?
If the merge is still in progress (conflicts unresolved), run
git merge --abort to cancel it and restore the pre-merge state. If the merge already completed locally, git reset --hard ORIG_HEAD returns the branch to its pre-merge position (unlike HEAD~1, it's also correct after a fast-forward - but it discards uncommitted work). If the merge is pushed, use git revert -m 1 <merge-hash>.Can I practice this online?
Yes. Open the terminal playground to run
git merge in a real shell in your browser - nothing to install. Coddy's free interactive Git course also covers merging and resolving conflicts step by step.