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

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


当前回答

如果您正在制定您的代码, 发现新的更改是一个巨大的错误或意外, 您可以简单地使用其他选项, 比如 :

git restore .

。指目录中的所有文件。

其他回答

根据我自己的类似经验,以上Strahinja Kustudidic提出的解决方案是迄今为止最好的。 正如其他人已经指出的那样,仅仅努力重设就会消除全部( 全部)未跟踪的文件, 其中可能包含很多您不想删除的文件, 例如配置文件。 更安全的做法是只删除即将添加的文件, 而对于这个事项, 您可能还想要检查任何即将更新的本地修改过的文件 。

因此,我更新了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 pull无错误 :

git fetch --all
git reset --hard origin/master
git reset --hard HEAD
git clean -f -d
git pull

警告警告警告警告:这个脚本非常强大,所以你可能会失去变化。

似乎大多数答案都集中在master然而, 分支中, 有几次我在两个不同的地方 研究同一个功能分支, 我希望在一个分支中重设一个, 在另一个分支中反映出来, 而不是跳过很多圈子。

依据综合RNA 的答复Torrek对类似问题的答复我已经想出了一个非常成功的计划:

git fetch
git reset --hard @{u}

从一个分支运行它 它只会重新设置你的地方分支 到上游版本。

这可以恰当地用在别名中(git alits) (Git) 。git forcepull)以及:

git config alias.forcepull "!git fetch ; git reset --hard @{u}"

或者,在你的.gitconfig文件 :

[alias]
  forcepull = "!git fetch ; git reset --hard @{u}"

尽情享受吧!

这将删除所有未承诺的更改, 然后拉动 :

git reset --hard HEAD
git pull

对于那些不喜欢的人reset我喜欢这个方法:


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