Skip to content

Volume ITechnology

13.11.3 — Remotes: Clone, Fetch, Pull and Push ​

Your laptop is stolen. Everything you built this year was in one folder on it.

Or the opposite: you finish a feature, and a teammate on another continent needs it. You cannot hand them your laptop.

Both problems have the same fix. You keep another copy of the repository on a server that everyone can reach. That server copy is called a remote. Git has four commands for moving work between your laptop and the remote: clone, fetch, pull and push. People mix them up, and a wrong guess causes most of the confusing Git messages you will ever see. This page makes each one clear.

1. A remote is just another copy ​

Here is the idea that removes most of the mystery.

In Git, every copy of a repository is complete. Your laptop has the whole history, not a thin window onto a server. The server copy has the whole history too. So does your colleague's laptop.

Your laptopfull historyyour branches:main, featureRemote ("origin")on GitHub or similarfull historythe shared meeting pointA colleague's laptopfull historytheir own branchespushfetchpushfetchgit clone copies the remote the first timeYou never edit the remote directly. You push to it, and others fetch from it.
Git has no single master copy. Every laptop holds the whole history. The remote is just one more copy that everyone agrees to treat as the meeting point. origin is the nickname your laptop gives it.

There is no "real" copy that outranks the others. The remote is simply the copy that the team agrees to treat as the meeting point. You put your work there. Others take it from there.

Services that host these meeting-point copies are GitHub, GitLab and Bitbucket. They give you a web page for the repository, accounts, and extra tools such as pull requests (Chapter 13.11.8). But the thing they host is an ordinary Git repository. A remote could also be a folder on a shared disk, or a bare repository on your own server.

Git gives each remote a nickname. The first one is nearly always called origin. It is only a name, not a magic word. It saves you from typing a long web address every time.

2. Getting a copy: git clone ​

To start work on an existing project, you clone it.

text
$ git clone git@github.com:ana/shop.git
Cloning into 'shop'...
done.
$ cd shop
$ git log --oneline
1cd2137 Start the shop

git clone does five things in one go:

  1. Makes a new folder named after the project.
  2. Downloads every commit of every branch from the remote.
  3. Creates the .git folder with a full copy of the history.
  4. Saves the address under the nickname origin.
  5. Switches you to the project's default branch (usually main) and fills the folder with its files.

You can clone into a different folder name (git clone <address> my-folder), or fetch only the recent history to save time (git clone --depth 1 <address>).

Ask Git what it remembered:

text
$ git remote -v
origin	git@github.com:ana/shop.git (fetch)
origin	git@github.com:ana/shop.git (push)

There are two lines because fetching and pushing can use different addresses. Almost always they are the same.

3. Proving who you are: SSH keys or tokens ​

Anyone can clone a public repository. But to push, the server needs to know who you are. There are two ways.

Way one: an SSH key. This is the common choice. You make a pair of files on your laptop: a private key that never leaves your machine, and a public key that you give to GitHub. When you push, your laptop proves it holds the private key that matches. No password is sent over the wire. Chapter 8.2 explains the mathematics behind this.

bash
ssh-keygen -t ed25519 -C "ana@example.com"      # (1)
cat ~/.ssh/id_ed25519.pub                        # (2)
ssh -T git@github.com                            # (3)
  1. Creates the key pair. Accept the default file location. A passphrase is a good idea: it protects the key if your laptop is stolen.
  2. Prints the public key. Copy that text. In GitHub, open Settings, then SSH and GPG keys, then New SSH key, and paste it in.
  3. Tests the connection. On success GitHub answers Hi ana! You've successfully authenticated, but GitHub does not provide shell access. That is the right answer, not an error.

Never share the file without .pub on the end. That is your private key.

Way two: HTTPS and a token. The address looks like https://github.com/ana/shop.git. GitHub no longer accepts your account password here. You create a personal access token in your account settings, and Git asks for it instead of a password. Setting git config --global credential.helper to your system's helper (the macOS keychain, the Windows credential manager, or cache) makes Git remember it so you are not asked every time. GitHub's own gh auth login command sets all this up for you.

Both work. SSH is a one-time setup that you then forget. HTTPS is easier behind some company firewalls. Pick one and stay with it.

4. Connecting a repository you made yourself ​

Often you start the other way round: you ran git init on your laptop, made commits, and now want a copy on GitHub. Create an empty repository there, then tell your local one where it lives:

bash
git remote add origin git@github.com:ana/shop.git
git push -u origin main

git remote add origin <address> records the nickname. The second command, covered in section 8, uploads your history.

Other remote commands you will sometimes need:

bash
git remote -v                          # list remotes and their addresses
git remote rename origin upstream      # change the nickname
git remote set-url origin <new-addr>   # the address moved
git remote remove origin               # forget it
git remote show origin                 # a detailed report on one remote

5. Remote-tracking branches: your notes about the remote ​

Here is the part that confuses beginners, so go slowly.

When you ran git branch earlier, you saw your local branches. After a clone, Git also keeps another kind: remote-tracking branches. They look like origin/main.

text
$ git branch -a
* main
  remotes/origin/HEAD -> origin/main
  remotes/origin/main

origin/main is not the real main on GitHub. It is a bookmark on your laptop that says: "the last time I spoke to the remote, its main was at this commit."

ABCorigin/mainmainHEADahead 1: one commit not yet pushed
origin/main is a bookmark on your laptop that remembers where main was on the remote the last time you talked to it. It does not move by itself. Only fetch, pull and push move it.

The figure shows origin/main one step behind main. That means you made one commit that you have not pushed yet. Git can tell you so:

text
$ git status -sb
## main...origin/main [ahead 1]

The two key facts:

  • A remote-tracking branch is read-only. You cannot commit to origin/main or switch to it for work.
  • It does not update by itself. Your laptop does not watch the internet. It only updates when you run fetch, pull or push.

That second fact explains a famous confusion. "My teammate said they pushed, but I do not see it." Of course you do not. Your bookmark still says the old thing, until you ask the remote.

6. Looking without touching: git fetch ​

git fetch goes to the remote, downloads any commits you do not have, and moves your bookmarks. That is all. Your own branches do not move, and your files do not change.

text
$ git fetch
From github.com:ana/shop
   1cd2137..205ce77  main       -> origin/main

Read the last line: the remote's main moved from 1cd2137 to 205ce77, and I updated my origin/main bookmark to match.

Now git status can tell you the truth:

text
$ git status
On branch main
Your branch is behind 'origin/main' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)

You can look at what arrived before you decide what to do with it:

bash
git log main..origin/main --oneline        # commits they have that I do not
git log origin/main..main --oneline        # commits I have that they do not
git diff main origin/main --stat           # which files differ
git log --left-right --oneline main...origin/main   # both lists at once

The two-dot form A..B means "commits reachable from B but not from A". It is the best way to answer "what is new over there?".

fetch is always safe. It cannot damage your work, because it never touches your branches or files. When in doubt, fetch first and look.

7. Fetch and merge in one step: git pull ​

git pull is two commands glued together:

text
git pull   =   git fetch   then   git merge origin/main
① Before: your main matches what you last heardABmainHEADorigin/main② After git fetch : the remote had one more commitABCmainHEADorigin/main③ After git merge origin/main (the second half of git pull)ABCmainHEADorigin/main
git fetch only updates your bookmark of the remote. Your own branch and your files do not change. git pull is fetch followed by a merge (or a rebase) in one command.

Read the figure from top to bottom. ① Your main and your bookmark agree. ② After fetch, the bookmark has moved to the new commit C, but main is still on B. ③ After the merge, main has caught up. In this case it was a fast-forward, because you had no commits of your own.

text
$ git pull
Updating 1cd2137..205ce77
Fast-forward
 README.md | 1 +
 1 file changed, 1 insertion(+)

If you also have commits of your own, the two lines of work have split, and Git must combine them. Newer versions of Git (2.33 and later) stop and ask you how:

text
$ git pull
From github.com:ana/shop
   1825185..f94fd4f  main       -> origin/main
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
fatal: Need to specify how to reconcile divergent branches.

The message is Git being polite. It is asking: "Do you want a merge commit, or do you want to replay your commits on top of theirs?" You can pick each time with a flag:

bash
git pull --no-rebase    # merge: creates a merge commit if both sides moved
git pull --rebase       # rebase: replays your commits on top of theirs (a straight line)
git pull --ff-only      # safest: only fast-forward, otherwise stop and let me think

Or choose once for every project:

bash
git config --global pull.rebase true

Merge keeps the history exactly as it happened. Rebase gives a cleaner straight line. Chapter 13.11.6 explains both in depth. For now, --ff-only is the cautious beginner choice: it never makes a surprise.

8. Sharing your work: git push ​

git push uploads your commits and moves the remote's branch forward to match.

The first time you push a new branch, use -u:

text
$ git push -u origin main
To github.com:ana/shop.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.

Break the command into words: git push to origin the branch main. The -u flag (short for --set-upstream) adds one more thing: it tells Git that your local main is linked to origin/main. From then on, a plain git push and a plain git pull already know where to go. You only need -u once per branch.

Without that link, Git does not know where a new branch should go:

text
$ git switch -c feature/coupons
$ git push
fatal: The current branch feature/coupons has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin feature/coupons

Git even prints the answer. If you grow tired of it, git config --global push.autoSetupRemote true makes git push do that automatically for new branches.

You can see which local branch tracks which remote branch:

text
$ git branch -vv
* feature/coupons 35173c0 [origin/feature/coupons] Add coupon code
  main            1825185 [origin/main] Add refund window constant

The part in square brackets is the upstream. It can also say ahead 2, behind 1 or gone.

9. When a push is rejected ​

This is the message that frightens every beginner. Here is how it happens.

Ana and Ben both cloned the project. Ana pushed a commit. Then Ben, who still has the old copy, made a commit of his own and tried to push.

text
$ git push
To github.com:ana/shop.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:ana/shop.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.
The remote (what Ana pushed)ABCmainBen's laptop: he started from B, not CABDmainHEADorigin/main✗ push rejected
Ana pushed commit C first. Ben made D on the same starting point. If Git accepted Ben's push, it would throw C away. So it says rejected and tells Ben to bring C in first.

Why does Git refuse? Look at the figure. The remote has commit C. Ben's main goes A, B, D, with no C. If Git accepted his push, the remote's main would move to D, and C would fall out of history. Ana's work would be silently erased.

So Git protects the shared copy with a simple rule: a push is allowed only if it adds to the remote's history, never if it replaces it. In technical words, the push must be a fast-forward of the remote branch.

You will see two slightly different labels after rejected:

  • (fetch first): the remote has commits your laptop has never even downloaded.
  • (non-fast-forward): you downloaded them (maybe with a failed pull), but your branch does not contain them.

The fix is the same for both. Bring their work in, then push.

text
$ git fetch
$ git status -sb
## main...origin/main [ahead 1, behind 1]
$ git pull --rebase
Successfully rebased and updated refs/heads/main.
$ git push
To github.com:ana/shop.git
   3d94b70..1825185  main -> main

ahead 1, behind 1 is the exact sign that the two sides have split. After pull --rebase, Ben's commit sits on top of Ana's, and now the push adds to the history, so it is accepted. If both changed the same lines, you get a conflict, which you resolve as shown in Chapter 13.11.2.

The wrong fix: --force ​

When a push is rejected, the internet will tell you to run git push --force. Do not. Force means "replace the remote with mine, I do not care what is there". It is exactly the silent erasure the rule was protecting against. If Ana's commit was the only copy, it is gone for everyone who has not fetched it.

There is one safer variant:

bash
git push --force-with-lease

--force-with-lease means "replace the remote, but only if it is still what I last saw". If someone pushed since, it refuses. This is the right tool in one honest situation: you rewrote your own branch's history (for example by rebasing it) and must overwrite your own old copy on the remote.

But understand what "last saw" means, because it has a trap. The lease compares the remote against your origin/main bookmark. A git fetch, or a git pull that failed after downloading, updates that bookmark. Git then believes you have seen the new commits, even if you never looked at them. Here is a real run:

text
$ git pull                       # Ana pushed meanwhile; this downloads her commit, then stops
fatal: Need to specify how to reconcile divergent branches.
$ git push --force-with-lease
To github.com:ana/shop.git
 + f94fd4f...176e838 main -> main (forced update)

Ana's commit f94fd4f was just overwritten, even with the safe flag. The pull had moved the bookmark, so the lease saw nothing unexpected. The habit that protects you: before any forced push, read what is on the remote with git log main..origin/main --oneline. If it prints commits you did not expect, stop.

10. Reading the signs: ahead, behind, diverged ​

You now know every word git status uses about remotes.

git status saysIt meansWhat to do
up to date with origin/mainYour branch and your bookmark agreeNothing
ahead by N commitsYou have N commits not pushedgit push
behind by N commitsThe remote has N you lackgit pull
have divergedEach side has commits the other lacksgit pull --rebase or merge, then push
upstream is goneThe remote branch was deletedDelete your local copy, or push it again

Remember that the answer is only as fresh as your last fetch. Run git fetch first if you want the real current picture.

11. Cleaning up remote branches ​

When a feature is merged, its branch on the remote is no longer needed. You can delete it from the command line:

text
$ git push origin --delete feature/coupons
To github.com:ana/shop.git
 - [deleted]         feature/coupons

Your local branch is still there. Git notices that its upstream disappeared:

text
$ git branch -vv
* feature/coupons 35173c0 [origin/feature/coupons: gone] Add coupon code

gone means "the remote branch this tracked no longer exists". Also, other people's laptops keep stale bookmarks to branches that someone deleted. Clean them with:

bash
git fetch --prune          # fetch, and delete bookmarks for branches that are gone
git config --global fetch.prune true    # do it on every fetch, automatically

Chapter 13.11.7 covers tags, which are pushed separately with git push --tags.

12. The four commands side by side ​

CommandTalks to the remote?Changes your branch?Changes your files?Changes the remote?
git cloneYesCreates itCreates themNo
git fetchYes (download)NoNoNo
git pullYes (download)Yes (merge or rebase)YesNo
git pushYes (upload)NoNoYes

If you remember one thing from this page, remember the fetch row. Download without touching anything: the safe way to look.

What the interviewer will push on ​

Remote questions are used to test whether you have worked in a team.

"What is the difference between git fetch and git pull?" This is the classic. fetch downloads and updates your remote-tracking bookmarks only. pull is fetch followed by a merge (or rebase) into your current branch. The tell of a strong answer is saying that fetch is always safe, and showing how you would inspect what arrived (git log main..origin/main). The weak answer says "pull gets the latest code and fetch also gets the latest code".

"What is origin?" The default nickname for the remote the repository was cloned from. It is a name, not a keyword. A repository can have several remotes with different names.

"What does git push -u origin main do?" It pushes and sets the upstream, so later git push and git pull need no arguments. The weak answer misses the second half.

"My push was rejected. Why, and what do you do?" Because the remote has commits I do not, and accepting would erase them. The fix is to bring those commits in (pull --rebase or pull then resolve), and push again. A very common wrong answer is --force. Saying "I never force-push a shared branch" is the right instinct.

"What is the difference between --force and --force-with-lease?" The lease refuses if the remote moved since you last fetched. Then show the depth: the lease trusts your bookmark, so a prior fetch can defeat it. Look at what is on the remote first.

"What is a remote-tracking branch?" A read-only local bookmark (origin/main) recording where the remote's branch was at the last contact. It does not update on its own.

One thing to volunteer: say that you set fetch.prune and pull.ff only (or pull.rebase) once, globally, so day-to-day pulling can never surprise you. Small settings like these show that you work with Git daily.

Recall

  • A remote is another full copy of the repository, usually on GitHub or GitLab. There is no master copy: every clone holds the whole history. origin is just the default nickname.
  • git clone downloads all commits and branches, creates .git, saves the address as origin, and checks out the default branch.
  • To push you need to prove who you are: an SSH key (private key stays local, public key goes to GitHub) or an HTTPS token.
  • origin/main is a bookmark on your laptop, recording where the remote's main was at the last contact. It is read-only and only moves on fetch, pull and push.
  • git fetch downloads and moves bookmarks; it never touches your branches or files, so it is always safe. git log main..origin/main shows what is new.
  • git pull = fetch + merge (or --rebase). On divergent branches choose with --no-rebase, --rebase or --ff-only, or set pull.rebase.
  • git push -u origin branch uploads and sets the upstream, so later push and pull need no arguments.
  • A push is rejected when it would erase remote commits you lack (fetch first or non-fast-forward). Fix: bring their work in (pull --rebase), then push. Never --force a shared branch.
  • --force-with-lease only checks your bookmark, so a prior fetch or failed pull defeats it. Read the remote with git log main..origin/main before forcing.
  • status words: ahead (push), behind (pull), diverged (integrate then push), gone (remote branch deleted). fetch --prune and push origin --delete clean up.

Self-test: What are the five things git clone does? · Why does origin/main not change until you run a command? · Why is fetch safe and pull not always? · Why does Git reject a push, and what exact condition must a push meet? · How could --force-with-lease still overwrite a teammate's commit?

Next: 13.11.4 is the page that removes the fear. Every way to undo something in Git, from a single file to a whole bad push, and the safety net that catches almost every mistake.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet