乐闻世界logo
搜索文章和话题

How do i clone all remote branches?

2个答案

1
2

First, when you clone a Git repository, the git clone command fetches all branches from the remote repository. However, locally, it only creates a single branch tracking the origin/master branch, named master. This means your local repository contains all the branch information for the remote repository, but to switch to these remote branches, you need to create corresponding tracking branches locally.

If you need to explicitly create and switch to tracking branches for all remote branches locally, follow these steps:

  1. First, clone the remote repository:

    shell
    git clone [remote-url]

    This creates references for all remote branches in the .git/refs/remotes/origin/ directory.

  2. Next, you can use git branch -a to view all branches, including remote branches.

  3. Then, for each remote branch, you can use the following command to create a local branch and establish tracking:

    shell
    git checkout -b [branch-name] origin/[branch-name]

    This command creates a new local branch named [branch-name] and sets it to track the corresponding remote branch.

For example, if the remote repository has a branch named feature, and you want to create and switch to it locally, you would execute:

shell
git checkout -b feature origin/feature

If you wish to automate this process, you can use the following script to create and switch to tracking branches for all remote branches after cloning:

shell
# Clone the repository git clone [remote-url] # Enter the repository directory cd [repository-name] # Iterate over all remote branches and create local tracking branches for branch in `git branch -r | grep -v '\->'`; do if [ "origin/HEAD" != "$branch" ]; then git checkout -b `echo $branch | sed 's/origin\\///'` $branch fi done # Switch back to the main branch git checkout master

This script clones the remote repository and creates local branches for all remote branches except HEAD, then switches back to the main branch. Note that you need to replace [remote-url] and [repository-name] with the actual remote repository URL and repository name.

2024年6月29日 12:07 回复

Using the --mirror option seems to correctly clone all remotely tracked branches. However, it configures the repository as a bare repository, so you must subsequently convert it back to a normal repository.

shell
git clone --mirror path/to/original path/to/dest/.git cd path/to/dest git config --bool core.bare false git checkout anybranch

Reference: Git FAQ: How to clone a repository containing all remotely tracked branches?

2024年6月29日 12:07 回复

你的答案