简体   繁体   English

从上次提交中检出文件,同时将其放入索引中

[英]Checking out a file from last commit while having it in index

I am a beginner in git.我是 git 的初学者。

What I've learned so far is that if I use git checkout -- <file> the file will be checked out from the staging area, if the file was staged, and from the last commit if the file was not staged.到目前为止,我学到的是,如果我使用git checkout -- <file>如果文件已暂存,则将从暂存区域检出文件,如果文件未暂存,则从上次提交中检出。

Now, if the file was staged after modification, and I try to replace the file in the working tree with the last committed version using git checkout HEAD -- <file> , it also removes the file from the staging area.现在,如果文件在修改后暂存,并且我尝试使用git checkout HEAD -- <file>将工作树中的文件替换为最后提交的版本,它也会从暂存区域中删除文件。

Is it possible to keep the initial modifications in the staging area and get the last committed version of the file in the working tree?是否可以将初始修改保留在暂存区域并在工作树中获取文件的最后提交版本?

To extract a file from a specific revision, we can use要从特定版本中提取文件,我们可以使用

git show $revision:$path

So in your case, you could try所以在你的情况下,你可以试试

git show HEAD:$path > $path

You could also replace git show with git cat-file -p .您也可以用git cat-file -p替换git show git show uses the pager by default, and git cat-file does not at all, even if a valid pager is specified. git show默认使用寻呼机,而git cat-file根本不使用,即使指定了有效的寻呼机。 But the pager doesn't matter here.但是寻呼机在这里无关紧要。

If is better to consider the newer ( Git 2.23, Q3 2022 ) git restore command when you want to... restore files.如果要更好地考虑更新的( Git 2.23, Q3 2022git restore命令,当您想...恢复文件。

It allows you to specify:它允许您指定:

  • the source (from which commit you want that file)源(您想要该文件的提交)
  • the destination (do you want to restore the file only in your working tree, the index or both?)目的地(您是否只想在工作树、索引或两者中恢复文件?)

That is:那是:

git restore --source $revision -- path/to/file

By default, it affects only the working tree, without impacting the staging area (cache).默认情况下,它只影响工作树,而不影响暂存区(缓存)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM