When you join a team, the path to your first contribution is the same almost everywhere: clone the repo, install its dependencies, create a branch off the main branch, make your change, push the branch, and open a pull request. You never commit straight to main, and you never start from an empty folder. The project already exists; you are joining it.
Below is that whole sequence with the reasoning behind each step, followed by the pieces you meet right after it: fork vs clone for projects you cannot push to, creating a pull request in detail, syncing a fork with upstream, the "remote origin already exists" error, and exporting and applying patches when there is no shared remote at all. If you are completely new to Git, start with Git for Beginners first.
The short version
git clone git@github.com:acme/widget-api.git
cd widget-api
npm install # or: pip install -r requirements.txt, bundle install, etc.
git checkout -b fix-login-redirect
# ...make your change, then:
git add .
git commit -m "Fix redirect loop on expired session"
git push -u origin fix-login-redirect
# then open a pull request on GitHubThat is the entire loop. The rest of this article explains each line.
Step 1: Clone the repository
Cloning downloads the full project, including its entire history, and sets up a connection (called origin) back to the server you cloned from.
git clone git@github.com:acme/widget-api.gitThat creates a widget-api folder containing the code. Use the SSH URL (git@github.com:...) if you have an SSH key set up, or the HTTPS URL (https://github.com/...) if you do not. If you have not set up a key yet, see adding an SSH key to GitHub; if you are unsure which to pick, I compared SSH vs HTTPS remotes separately.
Cloning is not the same as forking. On a team where you have write access to the shared repo, you clone. Forking makes your own server-side copy first and is the norm for open-source contributions where you do not have write access. I cover the distinction in fork vs clone below.
After cloning, move into the folder:
cd widget-apiStep 2: Install dependencies and read the README
The code is on your machine, but it will not run yet. Almost every project depends on packages that are not committed to the repo. The README tells you which command installs them and how to run the project locally.
npm install # Node.js
# pip install -r requirements.txt # Python
# bundle install # Ruby
# composer install # PHPWhy are these packages not in the repo? Because they are listed in a manifest (package.json, requirements.txt) and reinstalled on demand, and the actual files are excluded by .gitignore. Open the .gitignore early; it tells you a lot about what the project considers generated or local-only. If a node_modules folder or a .env file shows up as untracked, that is expected: those are ignored on purpose.
Run whatever the README lists as the test or dev command to confirm the project actually works on your machine before you change anything. Diagnosing a failing build is much easier when you know it failed because of your change, not because the project never ran in the first place.
Step 3: Make sure your main branch is current
Before you branch, make sure your local copy of the main branch matches the server. A fresh clone is current by definition, but if you cloned days ago, sync first:
git checkout main
git pullgit pull fetches the latest commits from origin and merges them into your local main. On a recent Git, that first pull can throw the divergent-branches reconcile prompt if your local and remote histories have diverged, so do not be alarmed when it asks you to pick a strategy. If you want to inspect what changed before merging, fetch first and look; I explain the difference in git pull vs git fetch.
If you already made edits before syncing, the pull can also stop with a complaint that your local edits would be overwritten. The cleanest fix is to stash them out of the way, pull to get main current, then continue.
Some teams call the main branch master instead of main. Check with git branch -a, which lists every local and remote branch.
Step 4: Create a branch for your work
You do your work on a branch, never directly on main. A branch is a cheap, isolated line of development. It lets you commit freely without touching the shared branch, and it is what a pull request is built on.
git checkout -b fix-login-redirectgit checkout -b creates a new branch and switches to it in one step. The name should describe the work: fix-login-redirect, add-csv-export. Many teams have a naming convention (feature/..., fix/...); the README or a CONTRIBUTING file will say. If branching itself is still fuzzy, I walk through it in Git branching explained.
Newer Git also offers git switch -c fix-login-redirect, which does the same thing with a clearer name. Both work; use whichever your team uses.
Step 5: Make your change, then stage and commit
Edit the files. When you are ready to record a snapshot, you stage the changes and then commit them. Staging is the step where you choose exactly what goes into the next commit, and it trips up a lot of newcomers, so it is worth understanding the staging area properly.
git status # see what changed
git add src/auth.js # stage specific files
git commit -m "Fix redirect loop on expired session"git add . stages everything that changed, which is fine for a focused branch. For a clean history, prefer staging only the files that belong to this change so unrelated edits do not sneak in. Run git status first, every time, so you know what you are about to commit.
Write a real commit message. "Fix redirect loop on expired session" tells a reviewer what happened; "stuff" and "fix" do not. A good message has a short summary line in the imperative mood. There is more nuance to it, which I cover in commit message conventions.
Made a typo in the message or staged the wrong file? It is recoverable. You can undo the last commit before you push, and if you have already deleted work, the reflog can recover lost commits.
Step 6: Push your branch
Your commits live only on your machine until you push them. The first push of a new branch needs -u to link your local branch to a new branch on origin:
git push -u origin fix-login-redirectThe -u (short for --set-upstream) tells Git that this local branch tracks origin/fix-login-redirect. After that first push, every later push and pull on this branch is just git push and git pull with no arguments. If you skip the -u, Git stops with:
fatal: The current branch fix-login-redirect has no upstream branch.That exact situation is covered in the current branch has no upstream branch.
Step 7: Open a pull request
Pushing the branch does not merge it. It just makes the branch visible on the server. To get your change into main, you open a pull request (PR): a request to merge your branch, which your teammates review before it lands. Right after a push, GitHub usually prints a URL in the terminal that opens the PR form directly. The full flow, from the compare view to merging, is in create a pull request below.
Fork vs clone
A fork is a copy of someone else's repository in your own account on the hosting platform, so you can change it without push access to the original. A clone is a local copy on your own machine. They are not alternatives: for a project you cannot push to, you fork on GitHub, then clone your fork.
| Fork | Clone | |
|---|---|---|
| Where the copy lives | On the hosting platform (GitHub, GitLab), in your account | On your local machine |
| What it is | A server-side copy of the whole repo under your namespace | A working copy with the full history and a .git folder |
| Is it a Git command? | No (a GitHub/GitLab feature, done in the web UI) | Yes (git clone) |
| When you need it | You want to contribute but lack push access to the original | You want to work with the files locally (any repo) |
| Do you get push access? | Yes, you own the fork, so you can push to it | Only if you had push access to the cloned repo already |
| Knows about the original? | Yes, GitHub tracks the upstream parent | Not automatically (you add a remote yourself) |
Cloning never grants permission; it only copies. A clone records the original URL as a push target, but if you lack write access the server rejects the push:
remote: Permission to some-org/some-project.git denied to your-username.
fatal: unable to access 'https://github.com/some-org/some-project.git/': The requested URL returned error: 403That is why forks exist. The decision is one question: do you have push access?
| Situation | What you do | Why |
|---|---|---|
| You are on the team with write access | Clone the shared repo, push branches to it | You can push branches and open PRs directly on origin |
| Open-source project, no write access | Fork first, then clone your fork | You cannot push to a repo you do not own; the fork is your writable copy |
| You want a local copy to read, not contribute | Clone (read-only) | Nothing to push; you just want the code and history |
The fork-and-pull-request workflow
- Fork the project on GitHub.
some-org/the-projectbecomesyour-username/the-project. - Clone your fork (not the original) and move into it:
git clone https://github.com/your-username/the-project.git, thencd the-project. - Add the original as
upstreamso you can pull in its changes later:
git remote add upstream https://github.com/some-org/the-project.git
git remote -vorigin https://github.com/your-username/the-project.git (fetch)
origin https://github.com/your-username/the-project.git (push)
upstream https://github.com/some-org/the-project.git (fetch)
upstream https://github.com/some-org/the-project.git (push)- Branch, commit, and push to your fork (
origin, which you own):git checkout -b fix-typo-in-readme, commit, thengit push origin fix-typo-in-readme. - Open a pull request from your fork's branch into the original project's
main. The maintainers review and merge it; you never needed push access to the original.
Common confusions: forking does not put anything on your computer (you still clone); you do not need a fork for repos you own or collaborate on; and once your PR is merged, you can safely delete the fork, because the merged commits now live in the original.
Create a pull request
A pull request is a request to merge the commits on one branch into another, paused so a teammate can review them first. On GitLab the same thing is called a merge request (MR); the mechanics are identical. The loop: branch off an up-to-date main, commit, push with -u, open the PR, request review, address feedback, merge. Never open a PR from main itself.
Open it and pick base and compare
There are three ways to reach the form: the "Create a pull request" link GitHub prints after your push, the yellow "Compare & pull request" banner on the repo page, or the "Pull requests" tab, then "New pull request". Either way you land on the compare view:
base: main <- compare: add-login-pagebase is where your work will merge into (usually main); compare is your branch. Getting these backwards is the single most common beginner mistake: if the diff looks empty or shows the wrong commits, you have them swapped. On GitLab it is "Merge requests", then "New merge request", with "source" (yours) and "target" (main).
Write a description that respects the reviewer
A good description answers three questions before the reviewer has to ask: what changes, why (link the issue; Closes #142 auto-closes it on merge), and how to check it.
## What
Adds the login page and client-side form validation.
## Why
Closes #142. Users had no way to sign in from the marketing site.
## How to test
1. Run the app, visit /login
2. Submit empty form -> see inline errors
3. Submit valid creds -> redirect to /dashboardKeep the PR small. A 60-line PR gets a careful review in ten minutes; a 2,000-line PR gets a rubber-stamp "LGTM" because nobody can hold that much in their head.
Review, drafts, and feedback
Add reviewers from the sidebar. With branch protection on main, a required-review rule means the PR cannot merge until someone approves, and CI checks show up as pass/fail status on the PR. A draft pull request (the dropdown next to "Create pull request", or a Draft: title prefix on GitLab) is visible and runs CI but cannot be merged and does not ping reviewers; click "Ready for review" when it is.
To address feedback, push more commits to the same branch; they appear on the open PR automatically, and since the upstream is set, it is just git push. If main moved on while the PR was open, merge or rebase it into your branch (the trade-offs are in git merge vs git rebase) and resolve any merge conflicts.
Merge and clean up
| Strategy | What it does | When I reach for it |
|---|---|---|
| Create a merge commit | Keeps every commit plus a merge commit | Long-lived feature branches where the history matters |
| Squash and merge | Collapses all branch commits into one | The default for most feature PRs; keeps main linear and readable |
| Rebase and merge | Replays each commit onto main, no merge commit | When each commit is already clean and you want them preserved |
For most day-to-day work I use squash and merge. Afterwards, delete the branch on GitHub and locally:
git switch main
git pull
git branch -d add-login-page| GitHub | GitLab | |
|---|---|---|
| Feature name | Pull request (PR) | Merge request (MR) |
| Branch dropdowns | base / compare | target / source |
| Draft mode | "Create draft pull request" | Draft: title prefix |
| Auto-close issue | Closes #142 | Closes #142 |
Plain Git cannot open a pull request; it is a hosting-platform feature. From the terminal, GitHub's CLI has gh pr create and GitLab has glab.
Sync a fork with upstream
A fork is frozen at the moment you made it, and the original project keeps moving. Your clone's origin points at your fork, so git pull only pulls from your own copy. To catch up, fetch from the upstream remote you added in the fork workflow and bring its commits into your branch:
git remote -v # check upstream is already there
# only if it is missing:
# git remote add upstream https://github.com/original-owner/project.git
git fetch upstream
git checkout main
git merge upstream/main
git push origin maingit fetch upstream downloads the original project's commits into remote-tracking branches like upstream/main without touching your files. If main has no commits of your own (the common case, since you work on feature branches), the merge is a fast-forward. You only ever fetch from upstream; you never push to it. If Git says remote upstream already exists, reuse it or fix its URL with git remote set-url upstream <url>.
You can rebase instead of merging (git rebase upstream/main), which replays any commits you have on main on top of upstream's latest for a linear history:
| Merge | Rebase | |
|---|---|---|
| History | Keeps a merge commit when branches diverged | Linear, no merge commit |
| Safety | Safer; never rewrites existing commits | Rewrites your local commits |
| Already-pushed commits | Fine | Avoid if those commits are already public |
| Best for | A shared main others have pulled | Keeping a personal fork tidy before a PR |
The pattern I follow: sync main, then branch off the freshly synced main, do the work, and push the branch with -u. Right before opening the PR, sync once more and rebase the feature branch onto the latest upstream so the PR sits on current code:
git fetch upstream
git checkout fix-typo-in-readme
git rebase upstream/main
git push --force-with-lease origin fix-typo-in-readme--force-with-lease refuses to overwrite the remote branch if it no longer matches what your last fetch recorded, so a push someone made since then is not silently clobbered. The check relies on your remote-tracking ref, so a background git fetch (some editors run one) can update it and defeat the protection; when that matters, pass the expected tip explicitly (--force-with-lease=fix-typo-in-readme:<sha>) or add --force-if-includes. Use it instead of a bare --force after any rebase. If a PR shows changes you did not make, your branch is based on stale upstream history, and this rebase narrows the diff back to your own work. If the merge errors with refusing to merge unrelated histories, the fork was re-initialized at some point and no longer shares a common ancestor with upstream. And if uncommitted edits block the sync, git stash, merge, then git stash pop.
Fix "remote origin already exists"
fatal: remote origin already exists. means you ran git remote add origin <url> but a remote named origin is already configured. You do not need to add it again. The usual causes: you cloned the repo (which sets origin for you) and then followed GitHub's "push an existing repository" snippet, you ran the same git remote add twice, or a folder you set up with git init still has an origin pointing at an old URL.
Check what is set first:
git remote -vorigin https://github.com/you/your-repo.git (fetch)
origin https://github.com/you/your-repo.git (push)If that is already the URL you want, there is nothing to fix. If not, update it in place:
git remote set-url origin https://github.com/you/your-repo.git
# or switch to SSH (add an SSH key to your account first):
git remote set-url origin git@github.com:you/your-repo.gitset-url changes only the URL and keeps branch tracking and fetch refspecs. When the remote's config is broken beyond its URL, remove and re-add it instead (git remote rm origin is the older spelling of remove):
git remote remove origin
git remote add origin https://github.com/you/your-repo.git| Situation | Use | Why |
|---|---|---|
origin exists, you just want a different URL | git remote set-url origin <url> | Surgical: changes only the URL, keeps tracking config |
| Switching HTTPS to SSH (or back) for the same repo | git remote set-url origin <url> | Same remote, different transport, no need to recreate |
| Remote config is broken or you want a clean slate | git remote remove then git remote add | Wipes the old definition entirely and rebuilds it |
You want a second remote alongside origin (e.g. a fork) | git remote add upstream <url> | Add under a new name, do not touch origin |
To confirm everything lines up, run git remote -v (the URL), git remote show origin (contacts the remote and lists its branches), and git branch -vv (which remote branch each local branch tracks).
Export and apply Git patches
Pull requests cover everyday team work, but sometimes there is no shared remote in the middle: moving a change between two repos that share no remote, sending a fix to a project you have no push access to, attaching a diff to a bug tracker, or the mailing-list workflow (git send-email) that the Linux kernel and other large projects still run on. For those, a patch file does the job, and there are two flavors. Picking the right one is the whole game.
| You want | Export | Apply | Authorship and history |
|---|---|---|---|
| A quick change moved over | git diff > my.patch | git apply my.patch | None preserved, no commit created |
| The commits recreated faithfully | git format-patch <range> | git am *.patch | Author, date, and message kept |
git diff plus git apply: a quick change transfer
git diff > my.patch captures your unstaged changes (the working tree compared with the index) into a plain unified diff. Anything you already ran git add on is left out, so if the patch must carry both staged and unstaged edits, use git diff HEAD > my.patch, which compares the working tree with the last commit. git apply my.patch in another checkout replays those line edits. No commit is created, nothing is staged, and the patch has no notion of who wrote it or why. It suits a one-off fix, a config tweak, or moving an experiment between two clones.
# In the source repo: write the unstaged changes to a file
git diff > my.patch
# Staged and unstaged changes together (everything since the last commit)
git diff HEAD > my.patch
# Only what is already staged (--staged is the same flag)
git diff --cached > staged.patch
# In the target repo: apply to the working tree only
git apply my.patch
# Or apply and stage in one step
git apply --index my.patchgit format-patch plus git am: preserve authorship
git format-patch writes one file per commit, each formatted as an mbox-style email complete with the author, date, subject (the commit summary), and full commit body. You pick the range of commits to export:
# The last N commits, numbered 0001-, 0002-, ...
git format-patch -3
# Every commit on feature that is not on main
git format-patch main..feature
# Just the most recent commit
git format-patch -1 HEAD
# Everything on this branch that is not on origin/main
git format-patch origin/main..HEAD
# Drop the files into a directory instead of the current folder
git format-patch -3 -o patches/
# A single combined file on stdout instead of one-per-commit
git format-patch main --stdout > feature.patchOn the receiving end, git am ("apply mailbox") reads those files, splits each back into its metadata and diff, and creates a commit per patch. Because the author and date rode along in the file, the replayed commits keep the original authorship rather than being attributed to whoever ran the command:
# Apply every patch file in order, recreating the commits
git am *.patch
# Add a Signed-off-by trailer if the project expects one
git am --signoff *.patchIf git am stops on a conflict, git am --abort rewinds you to where you started, git am --skip drops the current patch, and git am --continue resumes after you have resolved the conflict and staged the fix.
The short rule: git apply for a change transfer you will throw away after one apply, git format-patch plus git am when the work is real commits you want to land intact in another tree.
Check a patch first, and fall back to --3way
git apply --check tells you whether a patch will apply cleanly without changing anything. Run it first whenever you did not generate the patch yourself:
# Will it apply? No changes made, just success or an error.
git apply --check my.patch
# What files and how many lines would it touch?
git apply --stat my.patchA clean --check exits silently with status 0. A "patch does not apply" or a hunk error means the target tree has drifted from where the patch was cut. When that happens because the surrounding lines have moved, --3way falls back to Git's real merge machinery instead of failing outright:
git apply --3way my.patch
git am --3way *.patchIt needs the patch to record the blob identities it expects (the index lines that git format-patch and git diff include by default) and those blobs to exist locally. Instead of rejecting a hunk, Git does a three-way merge and leaves you ordinary conflict markers to resolve, exactly like a branch merge. If the commits you are about to export are noisy, squashing them first gives you cleaner patch files to hand over.
Common things that go wrong on your first day
A few errors are near-universal for newcomers. None of them mean you broke anything.
Please tell me who you areon your first commit means Git does not have your name and email configured yet. The fix is twogit configcommands, covered in fixing "Please tell me who you are".Permission denied (publickey)when cloning over SSH means your SSH key is not set up or not added to GitHub. See Permission denied (publickey).Support for password authentication was removedover HTTPS means GitHub wants a personal access token, not your account password. The fix is in password authentication was removed.failed to push some refsusually means the remote has commits you do not, so you need to pull first. See failed to push some refs.
When your branch falls behind main while your PR is open, you will eventually have to integrate the latest changes, which can produce a merge conflict. Conflicts are normal and resolvable; they are not a sign you did something wrong.
Where to go next
That loop, clone to PR, is the daily rhythm of working on a team. Once it is muscle memory, the next things worth learning are how your team integrates branches (merge vs rebase) and which overall branching model you are following (GitHub Flow vs Git Flow vs trunk-based). The full map of beginner Git topics lives on the Git for Beginners hub.
Sources
Authoritative references this article was fact-checked against.
- git-diff, official Git documentationgit-scm.com
- git-clone, official Git documentationgit-scm.com
- Pro Git: Working with Remotesgit-scm.com
- GitHub Docs: About pull requestsdocs.github.com
- About forks, GitHub Docsdocs.github.com
- Contributing to a project, GitHub Docsdocs.github.com
- GitHub Docs: Creating a pull requestdocs.github.com
- Pro Git: Contributing to a Projectgit-scm.com
- git-remote - Official Git documentationgit-scm.com
- Managing remote repositories - GitHub Docsdocs.github.com
- git-fetch: Official Git documentationgit-scm.com
- Syncing a fork: GitHub Docsdocs.github.com
- git-push - Official Git documentationgit-scm.com
- git-format-patch (official documentation)git-scm.com
- git-am (official documentation)git-scm.com
- git-apply (official documentation)git-scm.com





