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
OutcomeWhen
Fast-forwardMain has not moved — history stays linear
Merge commitBoth branches moved; preserves the true branching history
Squash mergeOne 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~3

Rewriting 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.

Remotes and collaboration Conflicts, stash and cherry-pick

Last refreshed 2026-09-17.