我有两个分支:

当地分公司(和我一起工作的那家) 远程分支(公共的,只有经过良好测试的提交才会去那里)

最近我把我当地的分公司搞得一团糟。

如何将本地分支完全替换为远程分支,以便从远程分支现在所在的位置继续工作?

我已经搜索了SO,在本地签出到远程分支没有任何影响。


当前回答

git branch -D <branch-name>
git fetch <remote> <branch-name>
git checkout -b <branch-name> --track <remote>/<branch-name>

其他回答

用远程取代当前本地分支的最安全、最完整的方法:

git stash
git merge --abort
git rebase --abort
git branch -M yourBranch replaced_yourBranch
git fetch origin yourBranch:yourBranch
git checkout yourBranch

存储线保存您尚未提交的更改。分支线将分支移动到不同的名称,释放原来的名称。获取行检索远程的最新副本。结帐行将原始分支重新创建为跟踪分支。

或者作为bash函数:

replaceWithRemote() {
    yourBranch=${1:-`git rev-parse --abbrev-ref HEAD`}
    git stash
    git merge --abort
    git rebase --abort
    git branch -M ${yourBranch} replaced_${yourBranch}_`git rev-parse --short HEAD`
    git fetch origin ${yourBranch}:${yourBranch}
    git checkout ${yourBranch}
}

它将当前分支重命名为replaced_master_98d258f之类的内容。

git reset --hard
git clean -fd

这为我工作-清洁显示它删除的所有文件。如果它告诉你你会失去零钱,你需要藏起来。

用远程分支替换所有内容;但是,只能从本地分支打开的同一个提交:

git reset --hard origin/some-branch

或者,从远程分支获取最新的并替换所有内容:

git fetch origin some-branch
git reset --hard FETCH_HEAD

顺便说一句,如果需要,你可以清除你还没有提交的未跟踪文件和目录:

git clean -fd

我有点惊讶居然没有人提到这一点;我几乎每天都用它:

git reset --hard @{u}

基本上,@{u}只是当前分支正在跟踪的上游分支的简写。例如,这通常等同于origin/[my-current-branch-name]。它很好,因为它是分支不可知的。

确保git首先获取远程分支的最新副本。

附注:在大多数shell中,命令会像写的那样工作,但如果你在PowerShell或csh中使用Git,你需要先转义特殊字符,尽管我也确认了它在这两种情况下都是作为字符串工作的,例如:

git reset --hard '@{u}'

选择的答案是绝对正确的,但它没有离开我与最新的提交/推送…

所以对我来说:

git reset --hard dev/jobmanager-tools
git pull  ( did not work as git was not sure what branch i wanted)

因为我知道我想暂时将我的上游分支设置几个星期到一个特定的分支(与我之前切换到/签出并进行了硬重置的分支相同)

所以是AFTER reset

git branch --set-upstream-to=origin/dev/jobmanager-tools
git pull
git status    ( says--> on branch  dev/jobmanager-tools