Browse cheat sheets · Git
Branching and Merging
Create, update, compare, merge, and clean up Git branches safely while preserving shared history and avoiding accidental divergence or destructive conflict resolution.
On this page
- Problem
- Quick answer
- Code / commands
- 1. Start a feature branch from an up-to-date main
- 2. Create a branch from a specific remote base
- 3. Show the current branch
- 4. List branches
- 5. Switch branches safely
- 6. Rename the current branch
- 7. Compare feature branch commits with main
- 8. See commits on main that your branch does not have
- 9. Compare code changes with main
- 10. Show changed files only
- 11. Fetch before deciding how to update
- 12. Merge latest main into the feature branch
- 13. Rebase feature branch onto latest main
- 14. Understand merge vs rebase
- 15. Merge another branch into the current branch
- 16. Fast-forward merge when possible
- 17. Force a merge commit intentionally
- 18. Preview whether a merge is likely simple
- 19. Abort a merge in progress
- 20. Detect an active merge
- 21. Resolve merge conflicts deliberately
- 22. List conflicted files
- 23. Inspect conflict hunks
- 24. Understand ours vs theirs during merge
- 25. Stage resolved files
- 26. Continue merge after conflicts
- 27. Merge a branch after it has been reviewed
- 28. Squash feature work into one local commit
- 29. Understand squash merge tradeoff
- 30. Push a new feature branch
- 31. Push after merging main into a feature branch
- 32. Push after rebasing a remote feature branch
- 33. Avoid rebasing shared integration branches
- 34. Delete a merged local branch safely
- 35. Check unmerged commits before deletion
- 36. Force-delete a local branch only when necessary
- 37. Delete a remote branch
- 38. Prune stale remote-tracking branches
- 39. Find local branches already merged into main
- 40. Find local branches not merged into main
- 41. Understand remote-tracking branches
- 42. Set branch upstream
- 43. Inspect ahead/behind state
- 44. Find the merge base
- 45. Show branch graph
- 46. Compare two branch tips directly
- 47. Do not merge stale main accidentally
- 48. Create a backup branch before complicated history changes
- 49. Use reflog if a branch move goes wrong
- 50. Keep feature branches focused
- What the result means
- What to look for
- Feature branch has unexpected commits
- Merge creates many conflicts
- Merge says “Already up to date”
- Remote branch changed after your rebase
- Branch deletion is refused
- Same conflict appears repeatedly
- Production notes
- Branch policy should match team collaboration
- Shared branches should avoid history rewriting
- Short-lived branches reduce conflict cost
- Merge conflict resolution is code review
- CI/CD usually runs on branch state, not intention
- Remote-tracking branches are snapshots
- Common mistakes
- 1. Creating a feature branch from stale main
- 2. Merging while on the wrong branch
- 3. Rebasing a branch teammates already use
- 4. Force-pushing after a normal merge
- 5. Choosing --ours or --theirs blindly
- 6. Deleting a branch with -D before checking unique commits
- 7. Treating squash merge as identical to normal merge
- 8. Comparing branch tips when you really want feature-only changes
- 9. Assuming origin/main is current without fetching
- 10. Keeping feature branches open too long
- Next step
- Related deep dives
Problem
You need to work on changes in parallel without breaking the shared branch.
Typical engineering workflows include:
- create a feature branch from the right base
- keep the feature branch current
- compare the branch with
main - merge changes safely
- resolve conflicts deliberately
- avoid accidental merge commits
- clean up local and remote branches
- understand when merging is safer than rebasing
The goal is to keep branch history understandable and shared work safe.
Quick answer
For a normal feature branch:
git switch main
git pull --ff-only
git switch -c feature/report-engine
Work and commit:
git add -p
git commit -m "Add report engine endpoint"
Before merging:
git fetch origin
git diff origin/main...HEAD
git log --oneline origin/main..HEAD
Update the feature branch using your team’s preferred policy:
git merge origin/main
or:
git rebase origin/main
Then push:
git push -u origin feature/report-engine
For shared branch history, merge or revert is usually safer than rewriting commits that teammates may already use.
Code / commands
1. Start a feature branch from an up-to-date main
git switch main
git pull --ff-only
git switch -c feature/report-engine
This avoids creating the branch from an outdated local main.
Use --ff-only to avoid creating an unexpected merge commit while updating local main.
2. Create a branch from a specific remote base
git fetch origin
git switch -c feature/report-engine origin/main
Use this when you want the branch to start directly from the latest remote-tracking main.
3. Show the current branch
git branch --show-current
Use before committing or merging if there is any doubt about where you are.
4. List branches
Local:
git branch
Local + remote-tracking:
git branch -a
With upstream tracking:
git branch -vv
Use -vv to see whether the branch is ahead or behind its upstream.
5. Switch branches safely
git switch feature/report-engine
Git may refuse if uncommitted changes would be overwritten.
Do not force branch switching just to “get past” the warning.
Commit, stash, or resolve the working-tree state intentionally.
6. Rename the current branch
git branch -m feature/new-name
If the old branch was already pushed, the remote branch does not rename automatically.
You will typically push the new name and remove the old remote branch separately.
7. Compare feature branch commits with main
git log --oneline origin/main..HEAD
This shows commits your current branch has that origin/main does not.
Use before opening or updating a pull request.
8. See commits on main that your branch does not have
git log --oneline HEAD..origin/main
If this returns commits, your branch is behind origin/main.
9. Compare code changes with main
git diff origin/main...HEAD
Three-dot syntax compares your branch with the merge base.
This usually represents the change set introduced by the feature branch.
10. Show changed files only
git diff --name-status origin/main...HEAD
Useful for quick scope checks.
Example:
M src/api.py
A src/report_engine.py
D src/legacy_report.py
11. Fetch before deciding how to update
git fetch origin
This updates remote-tracking refs without changing your working tree.
Then inspect:
git log --oneline --graph --decorate --all -20
Do not merge or rebase against stale origin/main.
12. Merge latest main into the feature branch
git merge origin/main
Use this when:
- preserving history is preferred
- the branch is already shared
- rewriting commits would be disruptive
This may create a merge commit if the histories diverged.
13. Rebase feature branch onto latest main
git rebase origin/main
Use when:
- the branch is primarily yours
- team workflow prefers linear history
- rewriting feature-branch commits is acceptable
Avoid casually rebasing commits teammates already depend on.
14. Understand merge vs rebase
Conceptually:
MERGE
A---B---C main
\ \
D---E---M feature
vs:
REBASE
A---B---C main
\
D'---E' feature
Rebase creates new commit IDs for replayed commits.
Merge preserves the original commits and adds merge history when needed.
15. Merge another branch into the current branch
git merge feature/other-work
Always confirm the current branch first:
git branch --show-current
Git merges into the branch you are currently on.
16. Fast-forward merge when possible
If the current branch has no unique commits:
git merge --ff-only feature/report-engine
This moves the branch pointer forward without creating a merge commit.
If fast-forward is impossible, Git stops instead of performing another merge strategy.
17. Force a merge commit intentionally
git merge --no-ff feature/report-engine
Use only if the repository workflow intentionally preserves feature-branch merge commits.
Do not add merge commits by default when the team prefers linear history.
18. Preview whether a merge is likely simple
git log --oneline --graph --decorate --all -30
and:
git diff HEAD...feature/report-engine
Git does not have a perfect dry-run for all merge outcomes, but inspecting divergence first reduces surprises.
19. Abort a merge in progress
git merge --abort
Use when:
- you started from the wrong branch
- conflicts are broader than expected
- you need to return to the pre-merge state
Do not manually reset files while a merge is active unless you understand the consequences.
20. Detect an active merge
git status
Git will report that conflicts exist or that a merge is in progress.
git status should be the first command after an interrupted merge.
21. Resolve merge conflicts deliberately
A conflicted file can contain:
<<<<<<< HEAD
current branch version
=======
incoming branch version
>>>>>>> feature/other-work
Edit the file to the intended final result.
Then:
git add path/to/file
When all conflicts are resolved:
git commit
or let Git complete the merge according to the current state.
Do not keep conflict markers in committed code.
22. List conflicted files
git diff --name-only --diff-filter=U
Use this during a large conflict resolution.
23. Inspect conflict hunks
git diff
During a merge conflict, Git shows unresolved sections.
Use this before choosing either side.
24. Understand ours vs theirs during merge
During a merge:
ours
→ current branch
theirs
→ branch being merged in
Example:
git checkout --ours path/to/file
or modern restore form:
git restore --ours path/to/file
Do not use --ours / --theirs blindly.
A correct resolution often combines both versions.
25. Stage resolved files
git add src/app.py
git add README.md
Then verify:
git status
The merge is complete only when every conflict is resolved and staged.
26. Continue merge after conflicts
Usually:
git commit
Git will provide a merge commit message.
Review it before saving.
27. Merge a branch after it has been reviewed
Typical local flow:
git switch main
git pull --ff-only
git merge --ff-only feature/report-engine
This works only if the feature branch is already based directly on latest main.
Otherwise the repository’s merge policy may require:
- merge commit
- squash merge
- rebase merge
Often this is handled by the Git hosting platform.
28. Squash feature work into one local commit
git merge --squash feature/report-engine
git commit -m "Add report engine"
This applies the feature changes to the working tree/index without creating a merge relationship to the feature branch.
Use only when squash history is the intended policy.
29. Understand squash merge tradeoff
Squash produces one new commit containing the final diff.
Benefits:
- compact main history
- easy feature-level revert
Tradeoff:
- individual feature commits are not preserved on
main - Git does not record a normal merge relationship to the feature branch
This affects later branch comparison and repeated merge behavior.
30. Push a new feature branch
git push -u origin feature/report-engine
After upstream is set:
git push
31. Push after merging main into a feature branch
git push
A normal merge does not rewrite existing feature commits, so a regular push is typically sufficient.
32. Push after rebasing a remote feature branch
If you rebased commits already pushed:
git push --force-with-lease
Prefer this over:
git push --force
Use only when rewriting that feature branch is acceptable.
33. Avoid rebasing shared integration branches
Do not casually rebase:
main
develop
release
shared team branches
because commit IDs change and collaborators may already have based work on them.
34. Delete a merged local branch safely
git branch -d feature/report-engine
-d refuses to delete a branch Git does not consider fully merged.
This is safer than -D.
35. Check unmerged commits before deletion
git log main..feature/report-engine
If this shows commits, verify they are intentionally disposable before deleting the branch.
36. Force-delete a local branch only when necessary
git branch -D feature/report-engine
This can remove the branch name even when unique commits remain.
Use only after confirming those commits are preserved elsewhere or no longer needed.
37. Delete a remote branch
git push origin --delete feature/report-engine
Remote deletion affects other collaborators.
Do it after merge/closure according to team workflow.
38. Prune stale remote-tracking branches
git fetch --prune
This removes stale references such as:
origin/feature/old-branch
when the corresponding remote branch no longer exists.
It does not remove local branches.
39. Find local branches already merged into main
git branch --merged main
Use this as a cleanup aid.
Still verify important branches before deleting them.
40. Find local branches not merged into main
git branch --no-merged main
This helps identify work that may still be unique.
41. Understand remote-tracking branches
origin/main is not the remote branch itself.
It is your local repository’s last fetched view of the remote branch.
Update it with:
git fetch origin
Do not assume origin/main is current if you have not fetched recently.
42. Set branch upstream
git branch \
--set-upstream-to=origin/feature/report-engine \
feature/report-engine
Usually git push -u handles this when first pushing a branch.
43. Inspect ahead/behind state
git status
or:
git branch -vv
For exact commit counts:
git rev-list \
--left-right \
--count \
origin/main...HEAD
Example:
3 2
means:
3 commits unique to origin/main
2 commits unique to HEAD
44. Find the merge base
git merge-base origin/main HEAD
This prints the common ancestor used for three-dot comparisons.
Useful for understanding branch divergence.
45. Show branch graph
git log \
--oneline \
--graph \
--decorate \
--all \
-30
Use this when the branch relationship is confusing.
46. Compare two branch tips directly
git diff main feature/report-engine
This compares the snapshots at the two branch tips.
This differs from:
git diff main...feature/report-engine
which compares from the merge base and is usually better for feature-branch review.
47. Do not merge stale main accidentally
Before merging a completed feature into local main:
git switch main
git fetch origin
git pull --ff-only
Then perform the intended merge.
This avoids integrating into an outdated local base.
48. Create a backup branch before complicated history changes
git branch backup-before-integration
Do this before:
- risky rebase
- complicated conflict resolution
- local branch surgery
Branch creation is cheap and provides a recovery pointer.
49. Use reflog if a branch move goes wrong
git reflog
Find the previous commit:
git show <commit>
Create a recovery branch:
git switch -c recovery <commit>
Reflog is particularly useful after accidental resets or rebases.
50. Keep feature branches focused
Prefer:
feature/report-engine
to contain one coherent body of work.
Avoid mixing:
- unrelated refactors
- dependency upgrades
- formatting across the entire repository
- separate feature work
Focused branches produce easier merges and fewer conflicts.
What the result means
| Operation | History behavior | Typical use |
|---|---|---|
git switch -c |
Creates new branch pointer | Start isolated work |
git fetch |
Updates remote-tracking refs | Inspect current remote state |
git merge |
Preserves both histories | Integrate branches safely |
git merge --ff-only |
Moves branch pointer only | Clean fast-forward integration |
git merge --no-ff |
Forces merge commit | Preserve feature-branch boundary |
git merge --squash |
Applies combined diff only | One commit for feature |
git rebase |
Rewrites replayed commit IDs | Linearize private feature history |
git branch -d |
Removes merged local branch ref | Safe cleanup |
git push --delete |
Removes remote branch | Remote cleanup |
git merge --abort |
Cancels active merge | Recover from wrong/unsafe merge |
The central decision is:
Need to preserve shared history?
→ merge
Need to linearize private feature history?
→ rebase can fit
What to look for
Feature branch has unexpected commits
Run:
git log --oneline origin/main..HEAD
and inspect the graph.
The branch may have been created from the wrong base.
Merge creates many conflicts
Likely causes:
- long-lived branch
- broad overlapping refactor
- stale feature branch
- many unrelated changes in one branch
Resolve correctness first, then consider changing branch workflow.
Merge says “Already up to date”
You may be on the wrong branch or merging in the wrong direction.
Check:
git branch --show-current
git log --oneline --graph --decorate --all -20
Remote branch changed after your rebase
Do not overwrite it blindly.
Fetch and inspect whether someone else pushed changes.
Branch deletion is refused
Git believes the branch contains commits not merged into the target history.
Inspect them before using -D.
Same conflict appears repeatedly
Long-lived divergence or repeated rebasing/cherry-picking may be causing recurring overlap.
Consider smaller branches and more frequent integration.
Production notes
Branch policy should match team collaboration
There is no universal best policy.
Common patterns include:
merge commits
squash merge
rebase + fast-forward
Pick one deliberately and enforce it consistently.
Shared branches should avoid history rewriting
Once others depend on the commit IDs, rewriting causes unnecessary coordination and risk.
Short-lived branches reduce conflict cost
The longer a feature branch diverges from main, the more likely large conflict resolution becomes.
Integrate frequently enough to keep differences manageable.
Merge conflict resolution is code review
A conflict is not a mechanical Git problem only.
The engineer must understand the intended combined behavior.
CI/CD usually runs on branch state, not intention
Before merging, confirm:
- correct branch
- expected commits
- clean working tree
- tests/build status
- no accidental files
Remote-tracking branches are snapshots
Always fetch before making integration decisions based on origin/*.
Common mistakes
1. Creating a feature branch from stale main
You begin with avoidable divergence.
2. Merging while on the wrong branch
Git merges into the current branch.
Check first.
3. Rebasing a branch teammates already use
This rewrites commit IDs and complicates their history.
4. Force-pushing after a normal merge
A merge normally does not require force push.
5. Choosing --ours or --theirs blindly
Correct conflict resolution may need both sides.
6. Deleting a branch with -D before checking unique commits
You can lose the branch pointer to unmerged work.
7. Treating squash merge as identical to normal merge
Squash does not preserve the same ancestry relationship.
8. Comparing branch tips when you really want feature-only changes
For pull-request-style review, three-dot comparison is usually more useful.
9. Assuming origin/main is current without fetching
Remote-tracking refs can be stale.
10. Keeping feature branches open too long
Long divergence increases conflict and review complexity.
Was this helpful?
What could be better?
Thanks — that helps me improve Javi Builds.
Stay in the loop
Get the Javi Builds updates you actually care about.
Check your inbox
I sent you a confirmation link. Your subscription will be active after you confirm it.