git checkout new remote branch when cloning with d

2020-06-22 08:36发布

问题:

After I did a clone of a repo, a new branch test has been added to the origin remote. But I still see:

$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

What git command/s should I use to get the following output:

$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
  remotes/origin/test

The git checkout remote branch question is not my question because that is happening after I see all the remote branch references.

I cannot clone the repo again because I have my local changes/commits in it.

So, how to bring the new remote branch references to my repo using git commands?

I am using a BitBucket repo that has the following branches:


Trials

git fetch does not work:

$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
$ git fetch
$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
$ git fetch origin 
$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

回答1:

A simple git fetch should be enough.

That will bring origin/test to your repo.

Then a git checkout -b test origin/test will declare that branch locally.


The OP Gabriel Petrovay confirms (in the comments) the source of the problem:

There is a slight change in the git config file.

  • In the newly cloned repo [remote "origin"] has fetch = +refs/heads/*:refs/remotes/origin/*
  • but the old repo has fetch = +refs/heads/master:refs/remotes/origin/master.

I kind of feel this is the issue.

It is indeed.

git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"

That should solve it.



回答2:

Found the problem!!!

A git clone with a depth 1:

git clone --depth 1 <repo>

will only need the master branch reference and the git repote config generated for this repo will be:

[remote "origin"]                                                                                                
   url = git@bitbucket.org:jillix/cctool.git
   fetch = +refs/heads/master:refs/remotes/origin/master

instead of:

[remote "origin"]                                                                                                
   url = git@bitbucket.org:jillix/cctool.git
   fetch = +refs/heads/*:refs/remotes/origin/*

This will make the fetch fail in bringing all the remote references.