How to Use git push -u: Simple Guide for Beginners
Use
git push -u <remote> <branch> to push your local branch to a remote repository and set it as the default upstream branch. This means future git push or git pull commands will know which remote branch to interact with automatically.Syntax
The command git push -u <remote> <branch> has three parts:
git push: Sends your local commits to the remote repository.-uor--set-upstream: Sets the remote branch as the default upstream for your local branch.<remote>: The name of the remote repository, usuallyorigin.<branch>: The name of your local branch you want to push.
Setting the upstream means you can later just run git push or git pull without specifying the remote or branch.
bash
git push -u origin mainExample
This example shows pushing a new local branch feature1 to the remote origin and setting it as upstream. After this, you can simply use git push or git pull without extra arguments.
bash
git checkout -b feature1 # Make some changes and commit them git add . git commit -m "Add feature1" git push -u origin feature1
Output
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 8 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 350 bytes | 350.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/user/repo.git
* [new branch] feature1 -> feature1
Branch 'feature1' set up to track remote branch 'feature1' from 'origin'.
Common Pitfalls
Common mistakes when using git push -u include:
- Forgetting to specify the remote and branch, which causes errors if the branch has no upstream set.
- Using
git pushwithout-uon a new branch, so future pushes require full branch names. - Confusing the remote name; usually it is
origin, but it can be different.
Always use git push -u origin <branch> the first time you push a new branch.
bash
git push feature1 # Error: fatal: The current branch feature1 has no upstream branch. # Correct way: git push -u origin feature1
Output
fatal: The current branch feature1 has no upstream branch.
Branch 'feature1' set up to track remote branch 'feature1' from 'origin'.
Quick Reference
Remember these tips for using git push -u:
- Use it once per new branch to link local and remote branches.
- After setting upstream, simple
git pushandgit pullwork without extra arguments. - The remote is usually
origin, but check withgit remote -v.
Key Takeaways
Use
git push -u origin branch to push and set the upstream branch in one step.Setting upstream lets you run
git push and git pull without extra parameters later.Always specify the remote and branch when pushing a new branch for the first time.
Check your remote names with
git remote -v to avoid mistakes.If you forget
-u, future pushes require full branch names or manual upstream setup.