我如何强制在 git pull 上覆盖本地文件 ? 我的本地仓库包含一个与服务器相同的文件名文件 。

错误: 未跟踪的工作树文件“ example. txt ” 会被合并覆盖


当前回答

对于那些不喜欢重置的人,我喜欢这样的做法:


git checkout branchname      # go to your branch
git fetch origin branchname  # fetch the remote
git checkout -b backup       # optionally, mark your remote as a backup
git branch -f branchname origin/branchname # force your local branch to be equal to the fetched origin/branchname


其他回答

我也有同样的问题,而且出于某种原因, 即使一个干净的Git -f -d也不会这样做。这就是为什么:由于某种原因,如果你的文件被Git忽略(通过.gitignore 项,我假设),它仍然费心于在稍后的拉动中覆盖这个文件,但清洁不会去除它,除非你加上 -x。

i 认为冲突有两种可能的原因,必须分别解决,而且只要我能够看出上述答案没有涉及两个问题:

未跟踪的本地文件需要删除, 手动( 安全) 或按照其他回答中的建议, 由 Git 清洁 - f - d 本地承诺删除, 不在远程分支的本地承诺也需要删除 。 最容易实现的方法是: git 重设 - hard 来源/ master (由您正在工作的分支替换“ 主机 ” , 并先运行 git 抓取来源 )

您可能会发现此命令有助于丢弃本地更改 :

git checkout <your-branch> -f

然后进行清理( 从工作树上移走未跟踪的文件) :

git clean -f

如果您想要除去未跟踪的文件之外, 还要删除未跟踪的目录 :

git clean -fd

基于我自己的类似经验, 以上strahinja kustudic 提供的解决方案远为最佳。 正如其他人指出的, 简单的硬重置将删除所有未跟踪的文件, 其中可能包含许多您不希望删除的文件, 比如配置文件。 更安全的是, 只删除即将添加的文件, 而对于这个事项, 您可能还想要检查任何即将更新的本地修改过的文件 。

因此,我更新了Kustudic的脚本, 仅此而已。 我也固定了一个打字(在原文中缺少的) 。

#/bin/sh

# Fetch the newest code
git fetch

# Delete all files which are being added,
# so there are no conflicts with untracked files
for file in `git diff HEAD..origin/master --name-status | awk '/^A/ {print $2}'`
do
    echo "Deleting untracked file $file..."
    rm -vf "$file"
done

# Checkout all files which have been locally modified
for file in `git diff HEAD..origin/master --name-status | awk '/^M/ {print $2}'`
do
    echo "Checking out modified file $file..."
    git checkout $file
done

# Finally merge all the changes (you could use merge here as well)
git pull

另一种解决的方法 就是先用 Git 隐藏来隐藏任何未承诺的更改, 然后运行

git pull --rebase=interactive -s recursive -X theirs

在交互式的重新基点中,您可以改变您本地所有不想要的放弃承诺, 这将摆脱它们, 并离开您在远程分支的头部, 而不引入合并承诺 。

现在,你可以运行git 藏品申请 如果你有本地藏品 更改了您想要带回来。