如何将远程 git 分支清楚地复制到本地存储库

我想要一个精确的“复制”一个远程分支“复制”到一个特定的本地分支。

例如,一个团队成员已经创建了一个实验性的特性,他已经将这个特性签入到远程存储库上名为 experiment的分支中。我希望能够在本地存储库中签出一个新的分支,并将 experiment分支原样“复制”到新签出的分支。

我不想把它和我的代码合并——我想完全覆盖我的代码,这样我就可以清楚地看到他在“实验”分支上做了什么。

如何“获取”(提取/拉取/无论什么...)一个其他人已经提交到远程存储库的远程分支到您自己的本地存储库,而不尝试在您自己的本地代码上执行合并?

124985 次浏览

If you don't care about merging:

git reset --hard <remote>/<branch_name>

This will exactly do what you want: no merging, no rebasing, simply put the local branch to exactly the same state as the remote is.

In your case however, you don't need that. You want to create a new local branch that has the same state as the remote, so specify the remote branch when creating the local one with git checkout:

git checkout -b <my_new_branch> <remote>/<branch_name>

If you want to use the same name locally, you can shorten that to:

git checkout <branch_name>

You would use git reset --hard if you already have a local branch (for example with some changes in it), discard any modifications that you made and instead take the exact version of the remote branch.

To be sure that you have the latest state of the remote branch, use git fetch <remote> before either checking out or resetting.

I don’t have enough rep to comment, but I’d like to add an example for those still struggling. In my example, I’m using Github as my remote and copying the branch to my Linux server environment/terminal.

First, you’ll want to run git fetch To make sure you’re up to date.

Using the example of

git checkout -b <my_new_branch> <remote>/<branch_name>

With a remote branch named “picklerick”

I ran

git checkout -b picklerick remotes/origin/picklerick

I probably could have just used remote/picklerick for my remote path, but this worked for me.

Suppose git remote command outputs origin as a result, then

git fetch origin remote_branch_name:local_branch_name

will create a local branch which is an exact copy of a remote branch you need to.

EDIT: There is an alternative more modern solution:

git switch remote_branch_name

the command will create a local branch with the same name as the specified remote branch.