To clone all remote branches in Git and set up local tracking branches, follow these steps:
1. Clone the Repository
git clone <repository-url>
cd <repository-directory>
2. Fetch All Remote Branches
git fetch --all # Retrieves all branches from the remote
3. List All Remote Branches
git branch -r # Shows remote branches (e.g., origin/main, origin/feature)
4. Create Local Branches Tracking All Remote Branches
Method 1: Loop Through Branches
git branch -r | grep -v '\->' | while read remote; do
git branch --track "${remote#origin/}" "$remote"
done
Method 2: Checkout Each Branch
# For each remote branch (excluding HEAD), create a local branch:
for branch in $(git for-each-ref --format='%(refname:short)' refs/remotes/origin); do
git checkout -b "${branch#origin/}" "$branch"
done
5. Verify Local Branches
git branch -a # Lists all local and remote branches
Example Workflow
# Clone the repo
git clone https://github.com/user/repo.git
cd repo
# Fetch all branches
git fetch --all
# Create local branches for all remote branches
git branch -r | grep -v '\->' | while read remote; do
git branch --track "${remote#origin/}" "$remote"
done
# Switch back to the default branch (e.g., main)
git checkout main
Key Notes
- Remote Name: Replace
origin
with your remote name (e.g.,upstream
). - Tracking Branches: Local branches will track their remote counterparts.
- Avoid Conflicts: Skip branches named
HEAD
(handled bygrep -v '\->'
).
Troubleshooting
- If you cloned with
--single-branch
, re-fetch all branches:
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
git fetch --all
Alternative: One-Liner
git clone <url> && cd <repo> && git fetch --all && git branch -r | grep -v '\->' | while read r; do git branch "${r#origin/}" "$r"; done
Now all remote branches exist locally, and you can switch to them with git checkout <branch-name>
.