Sub topic 11
Pushing and Setting an Upstream
This chapter assumes you can create, switch, and merge branches, and that your repository has a remote named origin. A remote is another copy of the repository, usually on a hosting service.
What an upstream is
A local branch and a remote branch are separate things. Git links them with an upstream setting. The upstream of feature/login is normally origin/feature/login, the remote-tracking branch from the previous chapter. Once the link exists, git status, git pull, and a bare git push know which remote branch to compare against.
Push a new branch
A new local branch has no upstream. Push it and set the upstream in one step:
git push -u origin feature/login
git branch -vv
git fetch origin
git log --oneline main..origin/main-u is short for --set-upstream. After it, git branch -vv shows each local branch with its upstream in square brackets. If the local branch is ahead or behind, the brackets also show ahead 2 or behind 1.
git fetch origin downloads new commits and updates the remote-tracking branches. It does not change your local branches or working files. The last command lists commits on origin/main that your local main does not have.
Daily use
With an upstream set, these commands need no arguments:
git pushsends new commits on the current branch to its upstream.git pullruns a fetch, then merges the upstream into your branch.git statusreports whether you are ahead of, behind, or diverged from the upstream.
You can also set the upstream later with git branch -u origin/feature/login.
Common errors
Push rejected with "non-fast-forward" or "fetch first": the remote branch has commits you do not have. Fetch, then merge or rebase, and push again.
"The current branch has no upstream branch": you skipped -u on the first push. Run the suggested git push --set-upstream origin <branch>.
Push after a rebase is rejected: rebasing rewrites commits, so your history no longer extends the remote's. Use --force-with-lease, not --force. It refuses to overwrite the remote branch if someone else has pushed since your last fetch.
Check your understanding
Exercise
You created fix/typo locally and committed twice. git push reports that the branch has no upstream. What single command pushes it and sets the upstream, and how do you confirm the link afterward?
Show answer
Run git push -u origin fix/typo. Then run git branch -vv. The line for fix/typo shows [origin/fix/typo] as its upstream.
Exercise
After git fetch origin, how do you list the commits on origin/main that your local main lacks?
Show answer
Run git log --oneline main..origin/main. The range main..origin/main selects commits reachable from origin/main but not from main.