Git Intermediate: Undo, Collaborate and Resolve
Remotes and Collaboration
In this lesson you will
- Clone a repository and inspect its remotes
- Explain the difference between fetch and pull
- Fix a rejected push
Introduction
Git is a distributed system. Everyone has a full copy of the repository, and they exchange commits with shared copies called remotes. Knowing exactly what push, fetch and pull do saves you from many confusing moments.
Clone
git clone copies a whole repository, with its history, to your computer.
Terminal
git clone https://github.com/your-name/project.git
cd project
git remote -vgit remote -v shows the remote, usually named origin, and its address.
Remote-tracking branches
Git keeps a read-only record of where each remote branch was the last time you checked, named like origin/main. Your own main branch is separate. You can compare them:
Terminal
git log main..origin/main --onelineThis lists commits that are on the remote but not yet on your local main.
Fetch versus pull
git fetchdownloads new commits and updatesorigin/main, but does not change your files or branches. It is always safe.git pullisfetchfollowed by a merge (or a rebase) into your current branch.
A careful habit is to fetch first, look at what arrived, then merge:
Terminal
git fetch
git log HEAD..origin/main --oneline
git merge origin/mainQuick quiz
Which command downloads new commits without changing your current branch or files?
Rejected push
If someone else pushed first, your push is rejected, because your history is behind theirs:
! [rejected] main -> main (fetch first)Fix it by bringing in their work first, then pushing again:
Terminal
git pull
git pushNever force a push on a shared branch just to make the error go away. It can erase other people's work. If you must rewrite your own branch, use git push --force-with-lease, which refuses to overwrite commits you have not seen.
Upstream and tracking
When you push a new branch the first time, set its upstream so later git push and git pull know where to go:
Terminal
git push -u origin add-footerForks and multiple remotes
When you do not have write access to a project, fork it on GitHub, clone your fork, and add the original as a second remote named upstream:
Terminal
git remote add upstream https://github.com/original-owner/project.git
git fetch upstream
git merge upstream/mainYou push to origin (your fork) and open a pull request to the original.
Try it yourself
Clone a public repository. Run git remote -v, then git fetch, then look at git branch -a to see the remote-tracking branches.
Summary
- Remotes are shared copies, and
origin/mainrecords where the remote branch was last seen. - Fetch is safe and only downloads. Pull is fetch plus a merge.
- A rejected push means you are behind. Pull first, and avoid force pushes on shared branches.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading