0

I've been practicing git checkout -- somefile.txt to checkout git files, in case I mess up. How does Git know which file gets checked out from which commit?

i.e.: I write git checkout -- index.html. How does Git know which commit to take index.html from, especially as your commit list gets larger and larger?

2
  • To clarify, do you mean git checkout -- index.html, with the space, or git checkout --index.html, without the space? Commented Aug 3, 2016 at 23:39
  • Changed it to spaced Commented Aug 3, 2016 at 23:40

1 Answer 1

3

Using git checkout with a path but without specifying a commit will check out the file from the index, i.e. the staging area. So for example if you have staged some changes to a file, and then modified it further and only want to undo those additional changes, then you can use git checkout -- some/path to undo those changes.

If your index is clean, i.e. nothing is reported as being staged when using git status, then the index will be equivalent to HEAD, the currently checked out branch (or commit). So this is a way to undo changes too.

Of course specifying a commit with git checkout will always use the file version from that exact revision, regardless of your index.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually that's wrong (I thought the same thing at first): git checkout -- some/path checks out the version from the index, not from the HEAD commit. In a lot of cases these are the same underlying blob anyway so that it makes no difference, though.
@torek You are absolutely right, I usually only think about situations with a clean index when writing answers despite me using checkout daily for exactly the purpose of undoing unstaged changes.. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.