How to Push a New Branch to Remote in Git
To push a new branch to a remote repository, first create and switch to the branch locally using
git checkout -b branch-name. Then use git push -u origin branch-name to upload the branch and set it to track the remote branch.Syntax
The command to push a new branch to a remote repository is:
git push -u origin branch-name
Here:
git pushuploads your commits to the remote repository.-usets the upstream tracking, linking your local branch to the remote branch.originis the default name of the remote repository.branch-nameis the name of your new branch.
bash
git push -u origin branch-nameExample
This example shows how to create a new branch called feature1 locally and push it to the remote repository.
bash
git checkout -b feature1 # Creates and switches to the new branch 'feature1' git push -u origin feature1 # Pushes 'feature1' to remote and sets upstream tracking
Output
Switched to a new branch 'feature1'
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 4 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 300 bytes | 300.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'feature1' on GitHub by visiting:
remote: https://github.com/your-repo/your-project/pull/new/feature1
remote:
To https://github.com/your-repo/your-project.git
* [new branch] feature1 -> feature1
Branch 'feature1' set up to track remote branch 'feature1' from 'origin'.
Common Pitfalls
Common mistakes when pushing a new branch include:
- Not creating or switching to the new branch locally before pushing.
- Forgetting the
-uflag, which means you have to specify the remote branch every time you push. - Using the wrong remote name instead of
origin.
Always ensure your local branch exists and you use -u to track the remote branch for easier future pushes.
bash
git push origin feature1 # Without -u, you must specify branch every time git push -u origin feature1 # Correct way to set upstream tracking
Quick Reference
| Command | Description |
|---|---|
| git checkout -b branch-name | Create and switch to a new branch locally |
| git push -u origin branch-name | Push new branch to remote and set upstream |
| git push origin branch-name | Push branch without setting upstream (less convenient) |
Key Takeaways
Use
git checkout -b branch-name to create and switch to your new branch locally.Push the new branch with
git push -u origin branch-name to set upstream tracking.The
-u flag links your local branch to the remote branch for easier future pushes.Always confirm you are on the correct branch before pushing to avoid mistakes.
Use
origin as the default remote name unless your remote is named differently.