Git Merge
Git merge combines the work from one branch into another. The typical use is merging a finished feature branch back into main. You always run git merge from the branch that should receive the changes.
Merging a Feature Branch
git switch main
git merge feature/blogUpdating a1b2c3d..4d5e6f7 Fast-forward blog.html | 1 + 1 file changed, 1 insertion(+) create mode 100644 blog.html
Fast-Forward Merges
If main has no new commits since the feature branch was created, Git simply moves the main pointer forward to the feature's latest commit. No new commit is needed. This is a fast-forward merge, and history stays a straight line.
Three-Way Merges
If both branches have new commits, Git combines them using their common ancestor and the two branch tips, and creates a merge commit with two parents.
git switch main
git merge feature/contact
git log --oneline --graphMerge made by the 'ort' strategy. contact.html | 24 ++++++++++++++++++++++++ * 8f9a0b1 (HEAD -> main) Merge branch 'feature/contact' |\ | * 3c4d5e6 (feature/contact) Add contact page * | 7e8f9a0 Update footer |/ * a1b2c3d Add README
Forcing a Merge Commit with --no-ff
Some teams prefer a merge commit even when fast-forward is possible, so the history clearly shows where each feature started and ended.
git merge --no-ff feature/search -m "Merge feature/search"Merge made by the 'ort' strategy.
Squash Merges
git merge --squash feature/x stages all the feature's changes as one set without merging history. You then commit them as a single tidy commit. GitHub and GitLab offer this as "Squash and merge" on pull requests.
A Simple Feature Workflow
- git switch main && git pull — start from the latest main.
- git switch -c feature/x — create your branch.
- Commit your work in small steps.
- git switch main && git merge feature/x — merge when done (or open a pull request).
- git branch -d feature/x — delete the merged branch.
Frequently asked questions
How do I merge a branch into main?
Switch to main with git switch main, update it with git pull, then run git merge your-branch-name.
What is a fast-forward merge?
When the target branch has not moved since the feature branch was created, Git just moves its pointer forward to the feature's tip, without creating a merge commit.
How do I undo a merge?
If not pushed, git reset --hard ORIG_HEAD returns to before the merge. If pushed, use git revert -m 1 <merge-commit> to create a commit that reverses it.