tezvyn:

Git Merge: Combining Development Histories

AI-drafted, machine-checkedSource: git-scm.comintermediate

Git merge combines separate lines of development into one branch. It creates a special merge commit that ties the two histories together, preserving the context of each. Use it to integrate a feature branch into your main line.

WHY IT EXISTS: To solve the problem of parallel development. Teams need a way to work on different features or fixes simultaneously in isolated branches and then combine that work back into a shared, stable branch. Git merge provides a structured, non-destructive way to perform this integration.

THE MENTAL MODEL: Think of git merge as weaving two threads of history together. When you merge branch feature into main, you're not just copying files. You're telling Git: "Take all the work done on feature since it split from main, combine it with the current state of main, and create a new, single commit that formally joins these two timelines." This new "merge commit" acts as a knot, holding the two threads together by having two parents.

HOW IT WORKS: When you run git merge <branch-name>, Git first finds the common ancestor of the two branches. It then creates a new commit that incorporates the changes from both branches. If Git detects that both branches have modified the same part of the same file, it stops and declares a merge conflict. It's then your responsibility to edit the files to resolve the conflict, git add the resolved files, and then git commit to finalize the merge.

WHEN TO USE IT: Use git merge when you want to preserve the history of a feature branch as a distinct, parallel line of work. The resulting merge commit serves as an explicit record that "work from branch X was integrated here," which is valuable for auditing and understanding project history. It is the default strategy used by git pull.

WHEN NOT TO USE IT: Avoid merging if you have uncommitted work in your current branch; commit or stash your changes first. A failed merge that needs to be aborted can have trouble reconstructing your pre-merge state if there were uncommitted changes. If you prefer a clean, linear history without extra merge commits, consider using git rebase instead.

ONE CANONICAL EXAMPLE: Your history has diverged. The main branch is at commit G, and your feature branch is at commit C. They both branched off from an earlier commit E. Running git checkout main followed by git merge feature will create a new commit H on the main branch. This commit H's content is the combination of the work in G and C, and its parents are both commit G and commit C, formally joining the two histories.

Read the original → git-scm.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.