简体   繁体   中英

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

I am a beginner in 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.

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.

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 show uses the pager by default, and git cat-file does not at all, even if a valid pager is specified. 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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