How to Create a New Git Branch

Create a new Git branch, switch to it, confirm you are on it, and push it to the remote so the branch tracks origin from the first push.

You want to work on a feature or fix without touching the main branch. Create a branch, commit on it, and push it when you are ready to share.

Create and switch to the branch

git switch -c feature-name

git switch -c creates the branch and checks it out in one step. Replace feature-name with something descriptive. Branch names cannot contain spaces; use hyphens instead.

On Git versions older than 2.23 the equivalent is:

git checkout -b feature-name

Both commands still work on current Git, and checkout -b appears in plenty of older guides.

Confirm which branch you are on

git branch
* feature-name
  main

The asterisk marks the current branch. git status shows it too, on the first line.

Commit your work

Make changes, then stage and commit as usual:

git add .
git commit -m "Describe the change"

Commits made now belong to feature-name and do not affect main.

Push the branch to the remote

git push -u origin feature-name

-u sets the upstream, so from now on a plain git push or git pull on this branch knows where to go. GitHub and GitLab usually print a link in the output to open a pull request.

Start from a clean, up-to-date main. A new branch begins at whatever commit you are currently on. Before creating one, run git switch main && git pull so the branch starts from the latest code rather than a stale copy. If git status shows uncommitted changes, commit or stash them first.

To create a branch without switching to it. git branch feature-name creates it and leaves you where you are. Switch later with git switch feature-name.

More Coding how-tos