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
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Create a Python Virtual Environment
- How to Install Node.js with nvm
- How to Make a Script Executable in the Terminal
- How to Print Hello World in JavaScript
- How to Print Hello World in Python
- How to Run a Local Web Server in One Command
- How to Undo the Last Git Commit