Why does `git checkout <branch> <file>` stage the change?

Viewed 3168

If I start from a clean working tree and run git checkout <branch> <file>, where <branch> has a different version of this file, I end up with a staged rather than an unstaged change.

What's the reason for this? Is this just for consistency with other commands like git mv, which you would expect to stage changes? Is it for convenience when using git checkout to resolve merge conflicts? Or is there some other rationale?

It seems mildly odd to me since just using git checkout <branch> <file> does not offer any indication of whether I plan to commit the change.

2 Answers

The Short Answer

  1. git checkout always copies items out of the index into the worktree.

  2. If you specify a commit other than the one you're on (e.g. the HEAD of another branch), checkout will always first copy the items from that commit into the index.

  3. Anything in the index that differs from HEAD will show as a "staged change". This is by definition.

See also Git checkout file from branch without changing index

Related