0
0
GitHow-ToBeginner · 3 min read

How to Track Remote Branch in Git: Simple Commands Explained

To track a remote branch in Git, use git checkout -b local_branch_name origin/remote_branch_name or git switch --track -c local_branch_name origin/remote_branch_name. This sets up your local branch to follow the remote branch, making it easy to pull and push changes.
📐

Syntax

Tracking a remote branch means linking your local branch to a branch on the remote repository. This allows Git to know which remote branch to compare and sync with.

  • git checkout -b <local_branch> origin/<remote_branch>: Creates a new local branch that tracks the specified remote branch.
  • git switch --track -c <local_branch> origin/<remote_branch>: Switches to a new local branch tracking the remote branch (modern alternative).
bash
git checkout -b <local_branch> origin/<remote_branch>
git switch --track -c <local_branch> origin/<remote_branch>
💻

Example

This example shows how to track the remote branch named feature from the remote called origin. It creates a local branch feature that tracks origin/feature.

bash
git fetch origin
# Create and switch to local branch 'feature' tracking 'origin/feature'
git checkout -b feature origin/feature
# Or using modern command:
git switch --track -c feature origin/feature

# Verify tracking status
git branch -vv
Output
* feature 123abc4 [origin/feature] Commit message here main 789def0 [origin/main] Commit message here
⚠️

Common Pitfalls

Common mistakes when tracking remote branches include:

  • Trying to track a remote branch that does not exist locally or remotely.
  • Not fetching updates before creating the tracking branch, causing errors.
  • Using git checkout without -b when the local branch does not exist, which leads to errors.

Always run git fetch first to update remote branch info.

bash
git checkout feature
# Error: pathspec 'feature' did not match any file(s) known to git

# Correct way:
git fetch origin
git checkout -b feature origin/feature
Output
error: pathspec 'feature' did not match any file(s) known to git
📊

Quick Reference

CommandDescription
git fetch originUpdate remote branch info from origin
git checkout -b origin/Create local branch tracking remote branch
git switch --track -c origin/Switch to new local branch tracking remote branch
git branch -vvShow local branches with tracking info

Key Takeaways

Use 'git fetch' before tracking to update remote branch info.
Create a local tracking branch with 'git checkout -b local_branch origin/remote_branch' or 'git switch --track -c local_branch origin/remote_branch'.
Tracking links your local branch to the remote branch for easy syncing.
Check tracking status with 'git branch -vv' to see which remote branch your local branch follows.
Avoid switching to a non-existent local branch without creating it first.