Git Branches: Create, Switch and List Branches
A branch is an independent line of work. You create one to build a feature or fix a bug, commit freely on it, and the main branch stays untouched until you decide to merge. Teams use branches so several people can work on different things at once.
What a branch really is
In Git a branch is just a movable label that points to a commit. Creating one is instant and costs almost nothing, no files are copied. When you commit on a branch, the label moves forward to the new commit. HEAD points to the branch you are on, which is how Git knows which label to move.
Creating and switching
git branchlists branches; the current one is marked with*.git switch -c feature-searchcreates a branch and switches to it in one step.git switch maingoes back tomain.git branch -d feature-searchdeletes a branch that has been merged. Git refuses if it has unmerged commits;-Dforces it.
Older tutorials use git checkout -b name and git checkout name. They still work, but git switch was added to Git specifically for changing branches and is harder to misuse, since checkout also restores files.
Files change when you switch
Switching branches updates the files in your working directory to match that branch. In the example, a file created and committed on feature disappears from the folder when we switch back to main, and comes back when we return. Nothing is lost: it lives in the feature branch's commits.
git init -q
echo "Home page" > index.txt
git add index.txt
git commit -q -m "Add home page"
git switch -c feature
echo "Search box" > search.txt
git add search.txt
git commit -q -m "Add search"
ls
git switch main
ls
git branch
git log --oneline --all Transcript (verified by our test suite in a fresh temp folder)
$ git init -q $ echo "Home page" > index.txt $ git add index.txt $ git commit -q -m "Add home page" $ git switch -c feature Switched to a new branch 'feature' $ echo "Search box" > search.txt $ git add search.txt $ git commit -q -m "Add search" $ ls index.txt search.txt $ git switch main Switched to branch 'main' $ ls index.txt $ git branch feature * main $ git log --oneline --all 88d79c2 Add search 64fbb15 Add home page
The final git log --oneline --all lists commits from every branch, and the branch names in parentheses show where each label points.
Uncommitted work
If you have uncommitted changes that would be overwritten, Git refuses to switch and tells you which files are in the way. Commit them, or set them aside with git stash and bring them back later with git stash pop.
Naming branches
Short, descriptive names in lowercase with hyphens work well: fix-login-redirect, add-dark-mode. Many teams add a prefix such as feature/ or bugfix/. Avoid spaces, which Git does not allow.
Summary
- A branch is a lightweight pointer to a commit; HEAD marks the current one.
git switch -c namecreates and switches;git switch namemoves.- Switching updates your files; commit or stash first.
Quiz: Branches