Create a Branch and Switch to It
git switch -c feature/login
Git creates the branch at your current commit and makes it the current branch. Uncommitted changes in your working tree come along, so you can start work on main and decide afterward that it belongs on its own branch. The older form does the same:
git checkout -b feature/login
How the two commands relate is explained in git checkout: switch branches and restore files.
Create a Branch Without Switching
git branch feature/login
The branch exists, but you stay where you are. This is handy for marking a point in history before an experiment, such as a risky rebase.
Start from Another Point
Add the starting point at the end. It can be a branch, a commit hash, or a tag:
git switch -c hotfix/payment main
git switch -c fix/old-bug a1b2c3d
git switch -c release/1.2 v1.2.0
Starting from a tag is the usual way to fix an old release without pulling in newer work.
Start from a Remote Branch
To work on a branch that a colleague pushed, fetch first, then switch by name:
git fetch origin
git switch feature/api
If exactly one remote has a branch of that name, Git creates a local branch that tracks it. The explicit form, useful when several remotes have the name:
git switch -c feature/api --track origin/feature/api
Push the Branch
git push -u origin feature/login
The push creates the branch on the remote, and -u sets it as the upstream, so later git push and git pull need no arguments. See git push: upload commits to a remote for the setting that does this automatically.
List Branches
| Command | What it shows |
|---|---|
git branch | Local branches |
git branch -r | Remote-tracking branches |
git branch -a | Both |
git branch -vv | Upstream and last commit |
The current branch is marked with an asterisk. git branch --show-current prints only its name, which is useful in scripts.
Naming Habits
- Prefixes: many teams group branches by type, such as
feature/,fix/, andrelease/. - Short and lowercase: words joined with hyphens, such as
fix/login-timeout. Add a ticket number if your team uses one. - Forbidden characters: no spaces, and none of
~,^,:,?,*, or[; no two dots in a row, no part that starts with a dot or ends in.lock, and no dot or slash at the end. - Prefix clashes: a branch named
featureand a branch namedfeature/logincannot exist side by side; Git refuses the second one.
To test a name before you use it:
git check-ref-format --branch "fix/login-timeout"
Common Problems
- A branch named that already exists: pick another name, or switch to the existing branch with
git switch. - Not a valid object name: the starting point is misspelled, or the repository has no commits yet. Make the first commit before you branch with
git branch. - Remote branch not found: run
git fetchfirst; your clone only knows remote branches it has fetched.
Later, you can rename a branch as shown in Git rename branch: local and remote, and remove it with Git delete branch: local and remote.