Git & Command Line Tutorial · Branching and Collaboration · Lesson 16 of 20
Remotes: clone, fetch, pull and push
Work with a shared repository: clone it, push your branch, fetch and pull others' work, track upstream branches, and handle a rejected push.
Remotes
A remote is another copy of the repository, usually on GitHub, GitLab or a company server. origin is the conventional name for the one you cloned from.
| Command | Does |
|---|---|
git clone <url> |
Copy a repository (all history) |
git remote -v |
List remotes |
git push -u origin feature/x |
Upload a branch and remember its upstream |
git fetch |
Download new commits without changing your files |
git pull |
fetch + merge (or rebase) into your branch |
git branch -vv |
Show each branch's upstream and ahead/behind counts |
If someone pushed first, your push is rejected: pull (merge, or rebase as in this example, their work into yours), then push again. Never use push --force on shared branches; --force-with-lease is the safer form for your own branches.
This example uses a folder as the "server" so it runs anywhere; with GitHub you'd use an https:// or git@ URL.
git init --bare --quiet -b main server.git # stands in for GitHub
git clone --quiet server.git ana && cd ana
echo "readme" > README.md && git add . && git commit -m "Initial commit" --quiet
git push --quiet origin main
cd ..
git clone --quiet server.git ben
cd ben && echo "ben's feature" > feature.txt && git add . && git commit -m "Ben adds a feature" --quiet
git push --quiet origin main
cd ../ana
echo "ana's change" > notes.txt && git add . && git commit -m "Ana adds notes" --quiet
git push origin main 2>&1 | grep -q "rejected" && echo "push rejected: the remote has a commit we don't have"
git pull --rebase --quiet origin main # replay our commit on top of Ben's
git push --quiet origin main
git log --oneline --graph
git branch -vv | sed 's/ */ /g'
Output
push rejected: the remote has a commit we don't have * 869a98d Ana adds notes * 7a05f65 Ben adds a feature * 69b567c Initial commit * main 869a98d [origin/main] Ana adds notes
Run this on your computer — see “Get Started” for setup.
Test yourself
Your push was rejected because the remote has commits you don't have. What do you do?
git push --forcePull (fetch and merge or rebase), then push againDelete the remoteClone again
Show answer
Answer: Pull (fetch and merge or rebase), then push again