我可以在两个文件上使用 "git checkout --" 吗?

56
是否可以使用git checkout --命令来丢弃多个文件的更改?如果可以,我该如何指定多个文件?

git checkout -- . - Anoop Thiruonam
6个回答

106

多次运行该命令

git checkout -- path/to/file/one
git checkout -- path/to/file/two

或者在同一行指定多个文件:

git checkout -- path/to/file/one path/to/file/two

您还可以指定整个文件夹,这将递归到其下面的所有文件。

git checkout -- path/to/folder
git checkout -- . # for the current path

8

我在用户的git repo目录中运行了find命令,不小心修改了该目录下的所有文件。

me@server:/home/me/gitrepo# git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   .bashrc
    modified:   dir/ec2-user.pem
    modified:   dir/readme.txt
    modified:   dir/root.pem
    modified:   dir/ec2-user.pem
    modified:   dir/readme.txt
    modified:   dir/root.pem
    modified:   dir/ec2-user.pem
    modified:   dir/ec2-user.pem.pub
    modified:   dir/readme.txt
    modified:   dir/root.pem

为了纠正我的错误,我运行了类似以下命令的内容,以查找所有已修改的文件并从主分支检出这些文件。 git status | grep modified | sed 's/^.*modified: //' | xargs git checkout

4

可能的选项包括:

git status --porcelain | cut -c4- | xargs git checkout

我该如何过滤此命令以忽略某些扩展名的文件? - Vicky Dev
你可以尝试添加一个管道语句,使用文件排除列表 (-f关键字用于grep来排除文件列表),或直接提供特定的文件名。单个文件: git status --porcelain | grep -vF 单个文件名.extention | cut -c4- | xargs git checkout。或多个文件: git status --porcelain | grep -vFf 排除列表.txt |cut -c4- | xargs git checkout。 - sshepel

3
使用以下命令:
   git checkout path/to/fileName path/to/fileName2 path/to/fileName3

这将允许您还原或放弃对文件 fileName、fileName2 和 fileName3 的更改。

注意:路径名称中的空格会导致 git 出现问题。在这种情况下,请使用单引号 '' 将路径名称括起来。


0

在一个文件中列出两个或多个文件。

随着 Git 2.25(2020 年第一季度)的推出,更多的命令学会了 "--pathspec-from-file" 命令行选项,我之前提到过对于 git commit

这意味着您可以使用 旧的令人困惑的 git checkout 命令,或者新命令(Git 2.23+)git restore 与一个文件列表(要检查/恢复的文件),而不是在不同的文件上多次重复相同的命令。

请查看 提交 a9aecc7, 提交 cfd9376, 提交 8ea1189, 提交 6fdc9ad, 提交 1d022bb, 提交 bebb5d6, 提交 21bb308 (2019年12月03日) 由 Alexandr Miloslavskiy (SyntevoAlex) 提交。
(由 Junio C Hamano -- gitster -- 合并于 提交 135365d, 2019年12月25日)

checkout, restore: 支持 --pathspec-from-file 选项

Signed-off-by: Alexandr Miloslavskiy

为简化起见做出的决策:

  1. 目前,即使 <file> 不是 stdin--pathspec-from-file 声明与 --patch 不兼容。这种用法并不是预期的。
  2. 不允许在参数和文件中同时传递 pathspec。

you must specify path(s) to restore 块被移动到下面以便能够测试 pathspec.nr,因为测试 argc 不再正确。

git switch 不支持这些新选项,因为它不接受 <pathspec> 参数。


Git 2.26(2020年第一季度)增加了更多的测试。

请参见提交 f94f7bd(2019年12月30日),作者为Alexandr Miloslavskiy(SyntevoAlex
(由Junio C Hamano -- gitster --提交 96aef8f中合并,2020年1月30日)

t: 添加对使用 --pathspec-from-file 时的错误情况的测试

建议者:Phillip Wood 签署者:Alexandr Miloslavskiy 签署者:Junio C Hamano


0

除了已经回答的,对于当前路径,我会这样做:

git checkout ./*

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接