読み物Git

Level: Basic

Working with Remote Repositories: Clone, Fetch, Pull, Push, and SSH

Connect repositories, understand remote-tracking branches, tell fetch from pull, handle rejected pushes, and authenticate safely with SSH keys or tokens on any platform.

Edeeson Opina8 min read

A Basic lesson card: lesson 5 of the Git & Version Control series, Working with Remote Repositories: Clone, Fetch, Pull, Push, and SSH, with the Miso fox holding a bowl of miso.

What you’ll learn

  • Add remotes and clone repositories
  • Read remote-tracking branches and ahead or behind status
  • Choose between fetch, pull with merge, and pull with rebase
  • Authenticate with SSH keys, credential managers, or scoped tokens
On this page
  1. Before you start
  2. What a remote is
  3. Clone: copying a repository
  4. Remote-tracking branches
  5. Push: sending your commits
  6. When a push is rejected
  7. Fetch and pull
  8. Authenticating to hosting platforms
  9. HTTPS with a token or credential manager
  10. SSH keys
  11. Working with more than one remote
  12. Common mistakes and troubleshooting
  13. Practical exercise: two people, one shared repository
  14. Key takeaways
  15. References
  16. What's next

Up to now your repository has lived on one computer. Collaboration starts when repositories exchange commits: you send yours to a shared repository, and fetch everyone else's. This lesson explains remotes and remote-tracking branches, the difference between fetch and pull, what happens when a push is rejected, and how to authenticate safely with SSH keys or HTTPS tokens. The examples use a shared repository on your own disk, so you can follow along without any account, then show how the same commands work with any hosting platform.

Before you start

You should know branches and merging from Understanding Git Branches, Merging, and Merge Conflicts. An account on a hosting platform is optional; everything except the SSH test can be practiced locally.

What a remote is

A remote is a named address of another repository: a URL or a path. The usual name for the main one is origin. Remotes can be:

  • an SSH address, such as git@code.your-company.test:team/recipes.git;
  • an HTTPS address, such as https://code.your-company.test/team/recipes.git;
  • a path on disk or a network share, such as ../shared.git.

The shared repository is usually a bare repository: one with no working tree, only the .git contents. Hosting platforms store bare repositories; you can create one locally to practice:

Shell
git init --bare -b main shared.git
cd my-project
git remote add origin ../shared.git
git remote -v
Text
origin	../shared.git (fetch)
origin	../shared.git (push)

Clone: copying a repository

git clone copies an entire repository, with all its history, sets up origin to point at the source, and checks out the default branch:

Shell
$ git clone ../shared.git ben
Cloning into 'ben'...
done.

Remember lesson 1: the clone is a full repository. Ben can commit, branch, and read history offline.

Remote-tracking branches

Your repository keeps a local memory of where the remote's branches were the last time you talked to it. These are remote-tracking branches, named like origin/main. You don't commit to them; Git updates them when you fetch or push.

Your local main usually tracks origin/main, which lets Git tell you whether you're ahead or behind:

Shell
$ git status -sb
## main...origin/main [behind 1]

"Behind 1" means origin/main has one commit your main doesn't. "Ahead 2" would mean you have two commits not yet pushed. Both can be true at once: the branches have diverged.

Push: sending your commits

Shell
$ git push -u origin main
To ../shared.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.

-u (or --set-upstream) sets tracking for the branch the first time you push it; afterwards, plain git push is enough.

When a push is rejected

If someone else pushed first, your push is refused:

Shell
$ git push
To ../shared.git
 ! [rejected]        main -> main (non-fast-forward)
error: failed to push some refs to '../shared.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. If you want to integrate the remote changes,
hint: use 'git pull' before pushing again.

Git protects the shared history: accepting your push would throw away the other person's commit. The fix is to bring their work into yours first, then push again. Never reach for git push --force to make the message go away; that overwrites their work. Lesson 10 explains the narrow cases where a careful force push (--force-with-lease) is appropriate, such as your own feature branch after a rebase.

Fetch and pull

git fetch downloads new commits and updates your remote-tracking branches. It never changes your own branches or your files:

Shell
$ git fetch
From ../shared
   df4d62b..02375ca  main       -> origin/main

After fetching, you can look before you integrate:

Shell
git log --oneline main..origin/main    # commits on the remote you don't have
git diff main origin/main              # what they change

git pull is git fetch followed by integrating origin/main into your branch, by merging or rebasing. It's convenient, but it does two things at once, and the second can create merge commits you didn't intend.

That's why lesson 2 suggested pull.ff = only. With it, git pull only fast-forwards; when your branch and the remote have both moved, it stops and asks you to choose:

Shell
$ git pull
hint: Diverging branches can't be fast-forwarded, you need to either:
hint:
hint: 	git merge --no-ff
hint:
hint: or:
hint:
hint: 	git rebase

You then decide deliberately: git merge origin/main keeps both lines of history with a merge commit, and git rebase origin/main replays your commits on top of theirs for a straight line (lesson 10 explains the trade-offs). Many teams set pull.rebase = true for everyday work on personal branches. Whichever you choose, choose it on purpose.

Authenticating to hosting platforms

Reading a public repository needs no credentials. Pushing, and reading private repositories, does. Hosting platforms no longer accept your account password for Git operations; there are two common options.

HTTPS with a token or credential manager

With an HTTPS remote, Git asks for credentials. Use either:

  • a credential manager, such as Git Credential Manager (included with Git for Windows and installable on macOS and Linux), which signs you in through the browser, supports multi-factor authentication, and stores tokens in your operating system's secure store; or
  • a personal access token created in the platform's settings, used instead of a password. Give it the narrowest scope and shortest lifetime that works, and prefer fine-grained tokens limited to specific repositories where the platform offers them.

Never put a token inside a remote URL (https://user:token@host/...); it ends up in .git/config, shell history, and logs.

SSH keys

SSH uses a key pair: a private key that stays on your computer and a public key you register with the platform. Create a modern Ed25519 key, protected with a passphrase:

Shell
ssh-keygen -t ed25519 -C "ada@laptop"
# Accept the default file (~/.ssh/id_ed25519) and enter a passphrase

This creates ~/.ssh/id_ed25519 (private: never share it, never commit it) and ~/.ssh/id_ed25519.pub (public: safe to share). Add the key to your SSH agent so you type the passphrase once per session:

Shell
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

Copy the contents of the .pub file into your account's SSH keys settings on the platform. Then test the connection; each platform documents its own test command and host, for example:

Shell
ssh -T git@github.com

The first time you connect, SSH shows the server's key fingerprint and asks whether to trust it. Compare it with the fingerprints the platform publishes in its documentation before typing "yes"; this is what protects you from connecting to an impostor. SSH then remembers the key in ~/.ssh/known_hosts.

Switch an existing remote from HTTPS to SSH with:

Shell
git remote set-url origin git@github.com:your-name/recipes.git

Some platforms also let you use security keys (ssh-keygen -t ed25519-sk) so the private key never leaves a hardware device.

Working with more than one remote

A repository can have several remotes. A common open-source setup: origin is your copy (fork) of a project, and upstream is the original:

Shell
git remote add upstream https://code.example-project.test/project/recipes.git
git fetch upstream
git switch main
git merge --ff-only upstream/main
git push origin main

The same idea lets you push one repository to two platforms, which lesson 15 uses for mirroring and backups.

Common mistakes and troubleshooting

  • Force-pushing over a rejected push. It deletes other people's commits from the remote. Fetch and integrate instead.
  • Pulling with uncommitted changes. Commit or stash first, so integration conflicts don't mix with unfinished work.
  • "Permission denied (publickey)." The platform doesn't recognize your key: check the public key is added to your account, the agent has the key loaded (ssh-add -l), and the remote uses the SSH address.
  • "Authentication failed" over HTTPS. You used your password. Use a credential manager or a token.
  • "Host key verification failed." The server's key doesn't match known_hosts. Don't blindly delete the entry; check the platform's published fingerprints first, because this is exactly the warning an impostor would trigger.
  • Wrong remote URL. Check with git remote -v.

Practical exercise: two people, one shared repository

  1. Create a bare repository shared.git and a repository ada with one commit. Add shared.git as origin and push with -u.
  2. Clone shared.git as ben. In ben, commit and push a change.
  3. In ada, run git status -sb, then git fetch, then git status -sb again. Explain the difference.
  4. In ada, commit a different change and try to push. Read the rejection.
  5. Integrate with git merge origin/main (or rebase), then push successfully.
  6. Optional, with a platform account: create an Ed25519 key with a passphrase, add the public key, verify the host fingerprint against the platform's documentation, and push over SSH.

Key takeaways

  • A remote is a named address of another repository; origin is the usual main one.
  • Remote-tracking branches such as origin/main record where the remote was when you last fetched.
  • fetch downloads without changing your work; pull is fetch plus merge or rebase.
  • A rejected push means others pushed first: integrate, don't force.
  • Authenticate with a credential manager, scoped tokens, or passphrase-protected SSH keys, and verify host fingerprints.

References

What's next

You've finished the Basic level: you can create, branch, merge, and share repositories on any platform. The Intermediate level begins with GitHub vs GitLab vs Bitbucket vs Codeberg: Understanding Git Hosting Platforms, which compares the platforms where repositories live.

See every lesson in Git & Version Control: From Fundamentals to Advanced Workflows