Push a Branch
Goal: Publish a local branch with git push, set its upstream, and read the message when a push is rejected.
Pushing is the mirror image of fetching: it sends your commits to the remote and asks it to move its branch to match yours.
The remote only agrees if that move is a fast-forward — if your branch already contains everything the server has. That one rule explains every rejected push you will ever see.
Publishing a branch for the first time
A new local branch exists only on your machine. git push -u origin feature/search does three things:
- uploads the commits that feature/search has and origin does not - creates feature/search on the server - sets your branch's upstream to origin/feature/search, so later you can type just git push and git pull
-u is short for --set-upstream. You only need it the first time.
What a successful push moves
Step 1 of 2
Two commits of yours are not on the server yet: main is two ahead of origin/main.
Step 1 of 2. Two commits of yours are not on the server yet: `main` is two ahead of `origin/main`.
A first push, with its upstream
$ git push -u origin feature/search
Enumerating objects: 7, done. To https://github.com/acme/weather-app.git * [new branch] feature/search -> feature/search branch 'feature/search' set up to track 'origin/feature/search'.
[new branch] means the remote did not have it before. The last line is -u doing its work: from now on git push on this branch knows where to go.
A rejected push
$ git push
To https://github.com/acme/weather-app.git ! [rejected] main -> main (fetch first) error: failed to push some refs to 'https://github.com/acme/weather-app.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again.
Nothing is broken and nothing was lost. Someone pushed a commit you do not have, so moving the server's main to yours would drop their work. Git refuses. Run git pull (or git fetch then git rebase origin/main), then push again.
Three ways out of a rejected push
git pull
- Merges their work into yours
- Adds a merge commit when both moved
- Always safe
git pull --rebase
- Replays your commits on top of theirs
- Keeps the history a straight line
- Fine while your commits are unpushed
git push --force
- Overwrites the remote branch
- Discards commits you do not have
- Almost never the right answer
Other everyday pushes
git push— the current branch to its upstreamgit push origin main— a named branch to a named remotegit push --delete origin feature/old-nav— delete a branch on the servergit push --tags— publish your tags, which are not pushed by default
