So you changed a file and now you want the original back (the original from the last commit). You want to undo the changes.

I do it like this:

git checkout HEAD — <filename>

ex: git checkout HEAD — README.md

also you can use FETCH_HEAD instead of HEAD like so:

git checkout FETCH_HEAD — <filename>

ex: git checkout FETCH_HEAD — README.md

HEAD would revert it to the last commit. FETCH_HEAD would revert it to the last commit that was pulled (fetched) / cloned. Therefore if you committed a change that you do not like, then do not revert using the HEAD method. The HEAD method will just take you back to the commit that you do not like, instead use FETCH_HEAD and it will take you to the file as it was received from the fetch (pull, clone etc).

Other sources mention more steps.

Source: http://stackoverflow.com/questions/16230838/git-is-it-possible-to-pull-just-for-one-file/25456627#25456627

Method1 (this is the accepted answer, it just has too many steps, so I dont want to use it):

git fetch
git checkout -m {revision} {file}
git add {file}
git commit

Method2 (my method is a variation of this, comment mentions it doesnt work, but it works for me):

git fetch {remote}
git checkout FETCH_HEAD — {file}

NOTE: your {file} can be relative or absolute path.

FETCH_HEAD vs HEAD

*HEAD: pulls file as it is from the last commit (current head of the git – this is updated with every pull & commit)

*FETCH_HEAD: pulls file as it is from the last pull (the head of the git when we last performed a git fetch, which was when we performed git pull, as git pull runs: fetch followed by merge or rebase depending on if you use –rebase or not)

Note: HEAD and FETCH_HEAD could ideally get the same file out because sometimes HEAD and FETCH_HEAD could point to the same place

Note: If you pushed your code to your repository & you think you messed up a file, you should use FETCH_HEAD to get it back from when you last pulled it. If you use HEAD you will just get the file from when you pushed, so it wont be what you want.

Leave a Reply

Your email address will not be published. Required fields are marked *