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?
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?
--no-ff to always create a merge commit, or --ff-only to require a fast-forward.How do I resolve a merge conflict?
<<<<<<<, =======, 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?
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?
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.