What is a tracking branch, and what is the `-u` flag for when pushing?
Show answer — try answering out loud first
A tracking branch is a local branch linked to a remote branch, its upstream. That link lets you use git push and git pull without typing the remote and the branch every time. The -u flag (or --set-upstream) creates that link the first time you push a branch.
When your local branch knows which remote branch it corresponds to, Git can do several things for you:
git pushwith no arguments knows where to upload.git pullwith no arguments knows where to download from.git statustells you "you're 2 commits ahead / 1 behindorigin/main".
That link is called the upstream. It's set the first time with git push -u origin nombre-rama. The -u is a shortcut for --set-upstream: "remember that this local branch follows this remote branch". After that, you no longer need to repeat the remote or the branch.
# First time you push a new branch: create the link with -u
git switch -c mi-feature
git push -u origin mi-feature
# Now local mi-feature follows origin/mi-feature
# From here, this is all you need:
git push # knows it goes to origin/mi-feature
git pull # knows where to fetch from
# See which upstream each branch has
git branch -vv
# * mi-feature 1a2b3c4 [origin/mi-feature] Agrega login
# main 5d6e7f8 [origin/main] Version inicial
# Set the upstream of an already existing branch
git branch --set-upstream-to=origin/mi-feature
Forgetting the -u the first time and having Git respond with an error like "fatal: The current branch has no upstream branch", without knowing why. The fix is to run git push -u origin nombre-rama the first time. Another mistake is thinking you need to add -u on every push: you only need it once, to create the link.
"A tracking branch is a local branch linked to a remote branch, its upstream. That link makes
git pushandgit pullknow where to go without me typing the remote and the branch every time, and makesgit statustell me how many commits I'm ahead or behind. The link is created the first time withgit push -u origin nombre-rama; the-uis--set-upstream. After that I just run plaingit pushorgit pull."
You created a new local branch feature-x and run a plain git push. Git responds with a "no upstream branch" error. Which command fixes it?
See answer
git push -u origin feature-x. The new branch doesn't have an upstream yet (no associated remote branch), so Git doesn't know where to upload it. The -u (--set-upstream) creates the link with origin/feature-x, and from that point on a plain git push and git pull are all you need.