Branches Overview
A branch is a movable pointer to a commit. Cheap, instant, local-first. Creating, switching, merging, deleting — branches are the unit of in-flight work.
Create, switch, rename, prune
EXAMPLE
# 1) List + create git branch # local branches git branch -a # local + remote git branch -vv # show tracking + last commit git branch feature/add-search # create from HEAD (doesn't switch) git switch -c feature/add-search # create + switch (modern) git checkout -b feature/add-search # same, classic syntax # 2) Switch git switch main # modern git switch - # last branch (like cd -) git checkout main # classic # 3) Branch from a specific point git switch -c hotfix v1.4.2 # from a tag git switch -c hotfix origin/main # from a remote ref git switch -c hotfix abc1234 # from a SHA # 4) Rename git branch -m old-name new-name # current branch git branch -m other-branch new-name # other branch git push origin -u new-name # republish git push origin --delete old-name # clean up remote # 5) Delete — safe vs forced git branch -d feature/done # only if fully merged into HEAD git branch -D feature/abandoned # FORCE — drops unmerged work git push origin --delete feature/done # 6) See what's NOT merged git branch --no-merged main # branches whose work is still floating git branch --merged main # safe to delete # 7) Track an upstream git branch --set-upstream-to=origin/main main git push -u origin feature/new # publish + set tracking # 8) Find the common ancestor / divergence git merge-base main feature/foo git log main..feature/foo # commits ON feature/foo not on main git log feature/foo..main # the other way # 9) Show every branch a commit lives on git branch --contains abc1234 # 10) Prune stale tracking refs (branches deleted on the remote) git fetch --prune git remote prune origin
Why it matters
git switch - jumps to the previous branch like cd -. Pair it with git fetch --prune weekly to keep your local refs honest.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
git branch # list local git branch -a # include remote-tracking git branch new-feature git switch new-featureTry it Yourself »
Discussion
Loading…