To make an existing Git branch track a remote branch, follow these steps:
1. Check Existing Remote Branches
First, ensure the remote branch exists:
git fetch origin # Fetch latest remote branches
git branch -r # List all remote branches
2. Link the Local Branch to a Remote Branch
Use the -u
(or --set-upstream-to
) flag to set the tracking relationship.
Command Syntax:
git branch -u <remote>/<remote-branch> <local-branch>
- Replace
<remote>
with the remote name (e.g.,origin
). - Replace
<remote-branch>
with the remote branch name. - Replace
<local-branch>
with your existing local branch name.
Example:
If your local branch is feature/login
and the remote branch is origin/feature/login
:
git branch -u origin/feature/login feature/login
Shortcut (if you’re already on the local branch):
git branch -u origin/feature/login
Alternative: Push and Set Upstream
If the remote branch doesn’t exist yet, create it and set tracking:
git push -u origin <local-branch>:<remote-branch>
Example:
git push -u origin feature/login:feature/login
3. Verify Tracking
Check if the branch is now tracking the remote:
git branch -vv
Output:
* feature/login a1b2c3d [origin/feature/login] Commit message
Troubleshooting
- Remote branch not found:
- Ensure you’ve run
git fetch
to update your local references. - If the remote branch is missing, push it first:
bash git push origin <local-branch>:<remote-branch>
- Wrong upstream branch:
- Reset the upstream:
bash git branch --unset-upstream # Remove current tracking git branch -u origin/desired-branch
Key Notes
- Use
git pull
/git push
without arguments once tracking is set. - To track a different remote branch later, repeat the
-u
step.