how to

Copy all upstream branches after forking only main branch

Mar 24, 2025
softwares-and-toolsgit
2 Minutes
312 Words

Copy all upstream branches after forking only main branch

If you’ve forked a Git repository but only have the main (or master) branch locally, you can fetch and track other remote branches from the original repository (upstream) into your fork. Here’s how:


Step 1: Add the Original Repository as upstream

If you haven’t already, add the original repo as a remote named upstream:

Terminal window
1
git remote add upstream https://github.com/original-owner/original-repo.git

Verify remotes:

Terminal window
1
git remote -v
2
# Should show:
3
# origin https://github.com/your-username/forked-repo.git (fetch/push)
4
# upstream https://github.com/original-owner/original-repo.git (fetch)

Step 2: Fetch All Branches from Upstream

Fetch all branches and their commits from the original repository:

Terminal window
1
git fetch upstream

This downloads all branches (e.g., feature, dev, etc.) but doesn’t create local copies yet.


Step 3: List Available Remote Branches

Check which branches exist upstream:

Terminal window
1
git branch -r # Shows remote branches (upstream/*)

Example output:

1
upstream/main
2
upstream/feature-x
3
upstream/dev

Step 4: Create Local Branches Tracking Upstream

For each branch you want to copy (e.g., feature-x), create a local branch that tracks the upstream version:

Terminal window
1
git checkout -b feature-x upstream/feature-x

This:

  1. Creates a local branch feature-x.
  2. Sets it to track upstream/feature-x.
  3. Switches you to the new branch.

Repeat for other branches you need.


Step 5: Push Branches to Your Fork (Optional)

To make these branches available in your fork (on GitHub/GitLab), push them to origin:

Terminal window
1
git push origin feature-x

Now they’ll appear in your fork’s remote repository.


Alternative: One-Liner to Copy All Branches

To copy all upstream branches to local and push them to your fork:

Terminal window
1
git fetch upstream
2
for branch in $(git branch -r | grep -vE "HEAD|main"); do
3
git checkout -b ${branch#upstream/} $branch
4
git push origin ${branch#upstream/}
5
done

This script:

  1. Fetches all upstream branches.
  2. Loops through each (excluding HEAD and main).
  3. Creates local branches and pushes them to your fork.

Key Notes

  • Tracking Branches: Local branches will track upstream (original repo). To track your fork instead:
    Terminal window
    1
    git branch -u origin/feature-x feature-x
  • Avoid Conflicts: If branches already exist locally, use git checkout -B to reset them.
  • Permissions: Ensure you have push access to your fork (origin).

Let me know if you need help with a specific branch or error!

Article title:Copy all upstream branches after forking only main branch
Article author:Julyfun
Release time:Mar 24, 2025
Copyright 2025
Sitemap