Git Branches

Git branches let you work on a feature or bug fix in isolation, without touching the stable code on main. A branch is just a lightweight, movable pointer to a commit, so creating one is instant and costs almost nothing.

Listing and Creating Branches

The asterisk marks the current branch. git switch is the modern command; older tutorials use git checkout branch and git checkout -b branch, which still work.

git branch                    # list local branches
git branch feature/login      # create a branch
git switch feature/login      # move to it
git switch -c fix/navbar      # create and switch in one step
* main
Switched to branch 'feature/login'
Switched to a new branch 'fix/navbar'

How Branches Work

Each commit points to its parent. A branch is a name pointing to one commit, and HEAD points to the branch you are on. When you commit, the current branch moves forward to the new commit while other branches stay where they were.

git switch -c feature/blog
echo "<h1>Blog</h1>" > blog.html
git add blog.html && git commit -m "Add blog page"
git log --oneline --graph --all
* 4d5e6f7 (HEAD -> feature/blog) Add blog page
* a1b2c3d (main) Add README

Switching with Uncommitted Changes

Git carries uncommitted changes with you when you switch, as long as they do not conflict with the target branch. If they would be overwritten, Git refuses. Commit them, or put them aside with git stash (covered later).

Renaming and Deleting Branches

git branch -m feature/blog feature/articles   # rename
git branch -d feature/articles                # delete (if merged)
git branch -D experiment                      # force delete unmerged
Deleted branch feature/articles (was 4d5e6f7).

Viewing Branch Details

git branch -v           # last commit on each branch
git branch --merged     # branches already merged into current
git branch -a           # include remote branches
  feature/blog 4d5e6f7 Add blog page
* main         a1b2c3d Add README

Branch Naming Conventions

  • feature/user-profile — new functionality
  • fix/login-redirect — bug fixes
  • hotfix/payment-crash — urgent production fixes
  • chore/update-deps — maintenance
  • Use lowercase and hyphens; include a ticket number if your team uses one (feature/APP-142-search).

Frequently asked questions

What is the difference between git switch and git checkout?

git switch only changes branches, while git checkout does many jobs (switching branches, restoring files, detaching HEAD). switch and restore were added in Git 2.23 to make these tasks clearer.

How do I create a new branch in Git?

Run git switch -c branch-name to create it from your current commit and switch to it. git branch branch-name creates it without switching.

How do I delete a branch locally and remotely?

Use git branch -d name locally and git push origin --delete name for the remote copy.