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:
1git remote add upstream https://github.com/original-owner/original-repo.gitVerify remotes:
1git remote -v2# 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:
1git fetch upstreamThis 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:
1git branch -r # Shows remote branches (upstream/*)Example output:
1upstream/main2upstream/feature-x3upstream/devStep 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:
1git checkout -b feature-x upstream/feature-xThis:
- Creates a local branch
feature-x. - Sets it to track
upstream/feature-x. - 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:
1git push origin feature-xNow 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:
1git fetch upstream2for branch in $(git branch -r | grep -vE "HEAD|main"); do3 git checkout -b ${branch#upstream/} $branch4 git push origin ${branch#upstream/}5doneThis script:
- Fetches all upstream branches.
- Loops through each (excluding
HEADandmain). - 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 1git branch -u origin/feature-x feature-x - Avoid Conflicts: If branches already exist locally, use
git checkout -Bto 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!