Search code examples
gitstaginggit-checkout

Retrieving an old version of a file using Git


Say I want to retrieve an old version of a file (filename.html) from a few commits ago. Am I right in thinking that I need to do

git checkout sha -- filename.html

(where sha is the hash of the commit I want)

But this puts the file in my staging index, and not my working directory, right? So if I now run git commit my repo will update to have the old file back in place, but my working directory will still have the newer file (which I don't wont any more).

I suppose I could do a git checkout -- filename.html to get the two back in sync, but is this best way to do it? This process seems like quite a drawn out one and one which could get messy quickly. Is there just a way to get the old version of filename.html back in my working directory without it getting 'stuck' in my staging index?

Thanks.


Solution

  • But this puts the file in my staging index, and not my working directory, right?

    It would put that old version both in the index and the working tree.

    if I now run git commit my repo will update to have the old file back in place, but my working directory will still have the newer file

    No, it will have the older version of that file.

    I suppose I could do a git checkout -- filename.html to get the two back in sync, but is this best way to do it?

    To get back to the latest version, you would have to:

    git reset HEAD -- filename.html # remove it from the index
    git checkout -- filename.html   # restore latest