Git Merge vs Rebase: Choose, Test, and Recover
Choose Git merge or rebase with a tested local lab. Compare commit history, resolve conflicts, understand push leases, and recover without guessing.
Use merge when preserving shared branch history matters. Use rebase to replay private work onto a new base when rewriting those commits is acceptable. Both integrate changes; they differ in ancestry and commit identity. Start clean, check who depends on the branch, and test the combined result.
What changes: ancestry, not just file contents
A branch is a movable reference to a commit. Suppose main and your feature branch both advanced after their common starting point. Merging main into the feature combines the histories and normally creates a commit with two parents. The existing feature commits keep their identities. A fast-forward is different: when one tip already descends from the other, Git can simply move the reference without creating a merge commit.
Rebasing a simple feature branch onto main reapplies its changes after the new main tip. Replayed commits have different parents and consequently different object IDs. That affects links to commits, review context, and collaborators who still have the original history. Rebase is not a command for making code more correct, and merge is not evidence of poor engineering.
The same final files can result from either operation while the history differs. Our lab makes that distinction observable: separate files avoid accidental conflicts, then a separate exercise deliberately changes the same line. This separates the integration decision from the mechanics of conflict resolution.
| Question | Merge | Rebase |
|---|---|---|
| Existing feature commit IDs | Preserved in the combined history | Replayed commits receive new IDs |
| Diverged branches | Usually a two-parent merge commit | A new sequence on the chosen base |
| Best starting assumption | Useful for shared history | Useful for private, unmerged work |
| Conflicts | Resolve the integration result | May resolve conflicts at multiple replay steps |
Source: Git merge reference ↗
Choose based on who depends on the branch
For an unpublished feature that only you use, rebasing can make the review sequence easier to follow. For a branch that teammates pull and extend, merging usually avoids making them repair their ancestry. A published personal branch may still be rebased under an agreed review policy, but “I own the branch name” does not prove nobody depends on its commits.
Ask three questions before acting: Is the working tree clean? Has anyone based work on these commits? Does the repository require a particular pull-request integration method? Branch protections and team policy take priority over personal preferences. When the answers are uncertain, stop rewriting and use the existing shared workflow.
Updating a feature branch and landing a pull request are separate decisions. You can rebase your private work locally and still land through a merge commit. A hosting service can also offer squash merging, which creates a combined change on the destination rather than preserving the entire feature sequence. Check the review platform’s configured behavior instead of treating every “merge” button as identical.
Lab: create two branches that genuinely diverge
Use a POSIX shell and a recent Git with switch and init -b support. This creates a new temporary repository; it does not touch an existing project or contact a remote. Run the following lab blocks in order in the same shell. The identity settings are local to this temporary repository. Keep the printed directory if you want to inspect it afterward.
The base commit contains README.md. The feature adds a separate file, while main adds a policy file. That gives both branches unique commits without making their file edits overlap. Two comparison branches start at precisely the same feature tip. A backup reference keeps that original tip available for inspection.
git_lab=$(mktemp -d)
cd "$git_lab"
git init -b main
git config user.name 'Learning Example'
git config user.email 'learning@example.invalid'
git config commit.gpgsign false
printf 'base\n' > README.md
git add README.md
git commit -m 'Base'
git switch -c feature
printf 'feature\n' > feature.txt
git add feature.txt
git commit -m 'Add feature'
git branch backup-feature
git branch merge-demo
git branch rebase-demo
git switch main
printf 'policy\n' > policy.txt
git add policy.txt
git commit -m 'Add policy'
printf 'Lab directory: %s\n' "$git_lab"Merge main into the first comparison branch
The current branch is the destination of git merge. Switching to merge-demo before merging main updates merge-demo; main stays where it was. The explicit --no-ff makes the intended merge-commit behavior clear, and -m avoids opening an editor.
The parent count is two. The ancestor check exits successfully because the original feature commit remains reachable. These checks describe history rather than relying on a decorative graph. You can also inspect git log --graph --oneline --all, but the exact hashes and graph spacing will differ between runs.
git switch merge-demo
git merge --no-ff main -m 'Merge main into feature'
git cat-file -p HEAD | grep -c '^parent '
git merge-base --is-ancestor backup-feature HEAD
# Expected parent count: 2; ancestor check exit status: 0Source: Git merge reference ↗
Rebase the second branch and compare the results
Rebase-demo still points to the original feature commit. Rebasing it onto main creates a new feature commit after the policy change. The backup branch remains unchanged. In this controlled example there are no merge commits, empty commits, or already-applied patches to complicate which changes are replayed.
The rebased tip has one parent, and its ID differs from backup-feature. Yet the tree comparison succeeds with no output: both approaches produced the same tracked files. This is a result of this example, not a guarantee for every real integration. Conflict choices, custom merge drivers, generated files, and different base changes can produce different results.
The command below also compares the old and new patch sequences with range-diff. For this one-patch example it should match the feature change across its different commit IDs. Review that mapping alongside tests; a patch comparison does not demonstrate that the application still works.
git switch rebase-demo
git rebase main
git cat-file -p HEAD | grep -c '^parent '
test "$(git rev-parse HEAD)" != "$(git rev-parse backup-feature)"
git diff --exit-code merge-demo rebase-demo
git range-diff main..backup-feature main..rebase-demo
# Expected parent count: 1; test and diff exit status: 0Source: Git range-diff reference ↗
Practice a conflict without risking project history
Start this second exercise from the lab’s base commit. Both branches replace the same README line differently. The rebase is expected to stop with a conflict and return a nonzero status. Run these commands interactively; an automation script using set -e must handle that expected failure explicitly.
Inspect status and diff before editing. To finish this example, replace the conflicted file with both intended lines, stage it, and continue. Git may open an editor for the replayed commit message. Alternatively, abort the operation while it is still in progress to return to the original conflict-feature tip. Choose one path; do not run abort after a successful completion expecting an undo.
git switch -c conflict-main main~1
printf 'main version\n' > README.md
git add README.md
git commit -m 'Change base line'
git switch -c conflict-feature main~1
printf 'feature version\n' > README.md
git add README.md
git commit -m 'Change feature line'
git rebase conflict-main
# Expected conflict. Inspect before choosing a resolution:
git status --short
git diff
# Option A: resolve, then continue:
printf 'main version\nfeature version\n' > README.md
git add README.md
git rebase --continue
# Option B instead, while the rebase is paused:
# git rebase --abortSource: Git rebase reference ↗
What the local test actually established
We ran these examples with Git 2.51.1 in a disposable repository. The merge result had two parents and retained the original feature commit as an ancestor. The rebased result had one parent and a different feature commit ID. Comparing the two final trees produced no difference. We also verified the expected conflict, successful abort, resolved continuation, and creation of a recovery reference from the original commit. No remote service or hosting-platform merge behavior was tested.
If your first comparison unexpectedly fast-forwards, check whether you actually committed the policy file on main. Merely creating two branch names does not make their histories diverge. If the tree comparison reports differences, inspect which branch received each command and whether you edited files between the two demonstrations. Do not copy expected output over a different result.
Treat the lab as a way to learn what to inspect in your own repository. It uses intentionally independent changes, followed by an intentionally overlapping edit. Real repositories add tests, review rules, signing requirements, submodules, and release processes. Those constraints belong in the integration decision even when the basic Git commands are familiar.
Resolve meaning, then rerun the relevant checks
A conflict marker tells you Git could not combine the text automatically. It does not tell you which business rule should win. Read the base change and the feature change, decide the combined intent, and check adjacent callers or configuration. During a rebase, ours/theirs terminology can be surprising because the operation is replaying your changes onto another base; inspect the actual text rather than blindly selecting a side.
Use rebase --skip only when you deliberately want to omit the current patch. It is not a general conflict repair. For a merge conflict, stage the resolved files and use git merge --continue, or git merge --abort to abandon an in-progress merge. Begin clean: reconstructing pre-existing uncommitted changes can be difficult after a conflicted merge.
After either operation, run the project’s meaningful checks against the combined state. For a documentation change that may mean links and rendering; for infrastructure it may mean validation and review of a new plan. A green check on the old feature tip does not validate its new base. Revisit deployment assumptions when the base changes environment settings or dependencies.
Source: Git merge reference ↗
A rejected push is a review signal
An ordinary push can reject rewritten history because it is not a fast-forward update. Do not respond with an unconditional force push. First fetch and inspect the remote branch, confirm ownership and coordination, and follow repository policy. Protected branches may forbid rewriting even when you supply a force option.
If an agreed workflow permits rewriting your personal feature branch, an explicit lease can require the destination to still point to the exact commit you reviewed. Git supports --force-with-lease=<refname>:<expected>, combined with an explicit source:destination refspec. If the expected remote value differs, the push is rejected. Capture the reviewed value before rewriting, rather than refreshing it merely to make a rejected push pass.
The shorthand --force-with-lease relies on remote-tracking information and can be undermined by a background fetch that updates it. Even an explicit lease is a concurrency check, not proof that nobody based work on the old commits. This guide’s lab deliberately has no remote and makes no force-push operation part of the copy-and-run exercise.
Recover by preserving evidence before moving references
If a completed rebase looks wrong, the pre-operation backup branch gives you a stable comparison point. Inspect git diff backup-feature rebase-demo and the patch mapping before changing anything else. Creating an additional rescue branch at a known commit preserves a handle while you investigate; it does not modify the current working files.
Without a backup, git reflog can show recent local reference movements. Find and inspect the relevant commit, then create a named branch at its verified ID. Avoid assuming HEAD@{1} always means “before the rebase”; other commands can add entries. Reflogs are local and expire, so they are a recovery aid rather than permanent shared backups.
Choose an integration method that preserves the collaboration contract, then validate the resulting code. The practical success criterion is a reviewable, tested change with understandable ancestry. A straight graph alone does not establish that result, and a merge commit alone does not prevent it.
Source: Git reflog reference ↗
Your next steps
- Run the temporary-repository lab and compare both ancestry and file trees.
- Before updating real work, check branch policy and whether collaborators depend on the existing commits.
- Preserve a recovery reference, review conflict resolutions, and rerun checks on the integrated state.
Sources & official resources
Linked resources checked on 2026-10-23. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →