iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Tracking Branches

A tracking branch is a local branch that has a remote-tracking counterpart it pushes to and pulls from by default. Without one, every push and pull needs the full ref spelled out; with one, plain `git push` and `git pull` Just Work, and `git status` shows you ahead/behind counts. Setting it up is one flag.

Set, inspect, and re-target tracking branches

EXAMPLE
# 1) On first push, --set-upstream (or -u) wires the tracking branch
git switch -c feature/checkout
git push -u origin feature/checkout
# now 'git push' and 'git pull' on this branch use origin/feature/checkout

# 2) Inspect tracking relationships
git branch -vv
#   main             a1b2c3d [origin/main] last commit subject
#   feature/checkout d4e5f6g [origin/feature/checkout: ahead 2] adding cart
#   stale-branch     7890abc [origin/stale: gone] old subject

# 3) The 'gone' marker means the remote branch was deleted
git fetch -p              # prune deleted remote refs from your local view
git branch -vv | awk '/: gone\]/{print $1}' | xargs -r git branch -D

# 4) Set tracking on an existing local branch (no first push needed)
git branch --set-upstream-to=origin/main main
git branch -u origin/feature/checkout    # short form

# 5) Change which remote a branch tracks (e.g. fork -> upstream)
git remote add upstream git@github.com:owner/repo.git
git fetch upstream
git branch -u upstream/main main

# 6) Remove the tracking relationship
git branch --unset-upstream feature/temp

# 7) Auto-setup-remote: never type -u again
git config --global push.autoSetupRemote true
# next 'git push' on a new branch creates origin/<same-name> and tracks it

# 8) Rebase tracking branches against their upstream on pull (cleaner history)
git config --global pull.rebase true
git config --global fetch.prune true

# 9) Check what is configured for a branch
git config --get-regexp '^branch\.feature/checkout'
#   branch.feature/checkout.remote origin
#   branch.feature/checkout.merge  refs/heads/feature/checkout

Why it matters

Turn on push.autoSetupRemote globally on day one. It is the single config flip that removes the most papercuts from daily git use, and it pairs cleanly with `fetch.prune` so deleted upstream branches stop cluttering `git branch -vv`.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Local branch tracks a remote one.
git branch -vv
git branch --set-upstream-to origin/main
Try it Yourself »

Discussion

Loading…