Sub topic 10
Remote-tracking branches
This chapter assumes you can commit, read git log, and create and switch local branches. It also assumes your repository has a remote, usually named origin, from git clone.
What a remote-tracking branch is
A remote-tracking branch is a local, read-only pointer that records where a branch on a remote was the last time you contacted that remote. Names look like origin/main. Git stores them under refs/remotes/origin/.
You never commit to origin/main directly. Git moves it only when you run git fetch, git pull, or git push. Between those commands it does not change, even if teammates push new work. It is a snapshot, not a live view.
Fetching updates
git fetch downloads new commits and moves the remote-tracking branches. It does not touch your local branches or your working tree.
git fetch origin
git branch -r
git log --oneline main..origin/maingit branch -r lists remote-tracking branches. The range main..origin/main means "commits reachable from origin/main but not from main", so the last command shows what you would receive.
Tracking relationships
A local branch can be set to track a remote-tracking branch. That link is the upstream. It lets git status, git pull, and git push work without extra arguments. git branch -vv shows each upstream and how far you differ from it.
git branch -vvTypical output:
* feature/login 3f2a1bc [origin/feature/login: ahead 2] Add login form
main 9d41e07 [origin/main: behind 3] Merge pull request #12"Ahead 2" means you have two commits the remote lacks. "Behind 3" means the remote has three commits you lack. Both numbers appear together when the branches have diverged.
Branches created by git clone or by git switch <name> (when only one remote has that name) track automatically. For a new local branch, set the upstream on the first push:
git push -u origin feature/loginCommon errors
- Stale information.
origin/mainreflects your last fetch, not the server now. Rungit fetchbefore judging whether you are behind. - Trying to commit on
origin/main. Checking it out gives a detached HEAD. Create a local branch instead withgit switch -c fix origin/main. - Leftover remote-tracking branches. Deleting a branch on the remote does not remove your
origin/old-branch. Rungit fetch --pruneto clean up. - Assuming
pullis a safe preview.git pullis a fetch followed by a merge (or rebase). Usefetchfirst when you want to inspect before integrating.
Exercise
You run git branch -vv and see [origin/main: ahead 1, behind 2] next to main. What does this mean, and which command shows the two commits you are missing?
Show answer
Your local main and origin/main have diverged: you have one commit the remote lacks and the remote has two commits you lack, as of your last fetch. Run git fetch origin to refresh, then git log --oneline main..origin/main to list the two missing commits.