Branching and merging
Creating branches, switching safely, merging versus rebasing, and keeping a messy history out of main.
Branches are cheap
A branch is just a movable pointer to a commit β creating one costs almost nothing, which is why branching per task is the normal workflow.
git branch feature/search
git switch feature/search # modern equivalent of checkout
# or create and switch in one step
git switch -c feature/search
git branch -a # list local + remote branches
git switch - # back to previous branchπ‘
Prefer
git switch and git restore over git checkout. Checkout does too many unrelated things; the newer commands each have one job.Merging
git switch main
git merge feature/search # creates a merge commit
git merge --ff-only feature/x # refuse unless it can fast-forward
git branch -d feature/search # delete once merged
git log --oneline --graph| Outcome | When |
|---|---|
| Fast-forward | Main has not moved β history stays linear |
| Merge commit | Both branches moved; preserves the true branching history |
| Squash merge | One clean commit for a messy feature branch |
Rebase vs merge
# replay your branch onto the latest main
git switch feature/search
git rebase main
# tidy up the last three commits interactively
git rebase -i HEAD~3Rewriting creates new commits with new IDs β accurate history versus honest history is a team decision, but the rule below is not.
β οΈ
Never rebase commits that others may already have pulled. Rewriting shared history makes teammates' branches diverge from the remote and leads to duplicated commits. Use merge there.
FAQ
Which should my team pick?
Either, applied consistently. Rebase pulls main into your feature branch to stay current; merge brings finished work into main. Many teams rebase locally and merge with a merge commit.
How do I undo a bad rebase?
git reflog shows where HEAD has been β find the pre-rebase commit and git reset --hard <sha>. Reflog entries expire, so act promptly.Related
Remotes and collaboration Conflicts, stash and cherry-pick
Last refreshed 2026-09-17.