How to Set Upstream Branch in Git: Simple Guide
Use
git push --set-upstream origin branch-name to set the upstream branch for your local branch. This links your local branch to the remote branch named branch-name on origin, enabling simple git push and git pull commands.Syntax
The command to set an upstream branch in Git is:
git push --set-upstream <remote> <branch-name>
Here, <remote> is usually origin, the default name for your remote repository. <branch-name> is the name of your local branch you want to link to the remote branch.
bash
git push --set-upstream origin branch-nameExample
This example shows how to create a new local branch and set its upstream branch on the remote repository.
bash
git checkout -b feature # Create and switch to a new branch named 'feature' git push --set-upstream origin feature # Push 'feature' branch and set upstream to 'origin/feature'
Output
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 250 bytes | 250.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
To github.com:user/repo.git
* [new branch] feature -> feature
Branch 'feature' set up to track remote branch 'feature' from 'origin'.
Common Pitfalls
Common mistakes when setting upstream branches include:
- Forgetting to specify
--set-upstreamor its shorthand-u, so the branch is not linked. - Using the wrong remote name instead of
origin. - Trying to set upstream on a branch that does not exist locally or remotely.
Always ensure your local branch exists and you have permission to push to the remote.
bash
git push origin feature # This pushes but does NOT set upstream git push -u origin feature # Correct: sets upstream branch
Quick Reference
| Command | Description |
|---|---|
| git push --set-upstream origin branch-name | Push local branch and set upstream to remote branch |
| git branch --set-upstream-to=origin/branch-name | Set upstream branch for current local branch without pushing |
| git push -u origin branch-name | Shorthand for setting upstream while pushing |
| git branch -vv | Show local branches with their upstream info |
Key Takeaways
Use 'git push --set-upstream origin branch-name' to link local and remote branches.
Setting upstream allows simple 'git push' and 'git pull' without extra arguments.
You can also set upstream without pushing using 'git branch --set-upstream-to'.
Check upstream branches with 'git branch -vv' to confirm linkage.
Always ensure the branch names and remote names are correct to avoid errors.