1

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?

Francisco Puga
  • 23,869
  • 5
  • 48
  • 64
Urooj
  • 151
  • 7
  • Note that a file that's in the commit you checked out earlier *is already staged*. It's just that the staged copy *matches the committed copy*. So `git status` doesn't bother to mention it: if `git status` mentioned every staged file, including those that match, and you have 10000 files in each commit (not at all unusual), every `git status` would list all 10k files. So `git status` only tells you about the *differing* files. – torek Jun 22 '22 at 09:49
  • Still, the fact that every file is *already in the index* means that `git checkout -- ` erases working-tree changes that have not been `git add`-ed. That's why you might want to use `git show` as in [ElpieKay's answer](https://stackoverflow.com/a/72710916/1256452). – torek Jun 22 '22 at 09:55

2 Answers2

0

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.

ElpieKay
  • 27,194
  • 6
  • 32
  • 53
0

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

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250