我有两个分支:

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

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

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

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


当前回答

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

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 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 branch -D <branch-name>
git fetch <remote> <branch-name>
git checkout -b <branch-name> --track <remote>/<branch-name>

这就像三步一样简单:

删除本地分支:git branch -d local_branch 获取最新的远程分支:git Fetch origin remote_branch 基于远端分支重建本地分支: Git checkout -b local_branch origin/remote_branch

如果你想要更新当前未签出的分支,你可以这样做:

git fetch -f origin rbranch:lbranch

确保您已经签出了要替换的分支(来自Zoltán的评论)。 假设master是你要替换的本地分支,而“origin/master”是你想重置到的远程分支: Git重置-硬源/主

这会将您的本地HEAD分支更新为与origin/master相同的版本,并且——hard也会将此更改同步到索引和工作区中。