Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between git checkout HEAD -- filename and git checkout -- filename

Let's begin with a situation.

  1. I stash some changes (5 files) git stash
  2. Change some files
  3. Commit the changes git commit -m "Commit message"
  4. Get the changes back from stash git stash apply

I receive a merge-conflict in 2 files because of the commit. I no longer want the changes in those 2 files So I tried to revert those changes.

I did git checkout -- background.js

It failed with error

error: path 'src/background/background.js' is unmerged

But then I read this SO post and tried

git checkout HEAD -- background.js

It works successfully. It happened with me for both the files. I want to understand the difference bewteen

git checkout -- file AND git checkout HEAD -- file

like image 359
Sachin Avatar asked Oct 01 '22 05:10

Sachin


1 Answers

Normally there isn't much of a difference. The key is that you had conflicts to resolve. From the man pages http://csurs.csr.uky.edu/cgi-bin/man/man2html?1+git-checkout

git checkout [--patch] [] [--] ...

...

The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using -f will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using --ours or --theirs. With -m, changes made to the working tree file can be discarded to re-create the original conflicted merge result.

You were using checkout this way when it was failing. So by design, the checkout will fail due to the unmerged changes (not resolving the conflicts). Adding the HEAD told git which "branch" to use and so will actually checkout the file.

HEAD refers to the specific SHA that you are at in your repo. So you are telling git where to pull the files from in the same way that you would for a different branch.

like image 82
Schleis Avatar answered Oct 15 '22 05:10

Schleis