5

I want to checkout a single file from a git repository to a different location (other than working dir) and leave my current working dir as it is. And I want git to checkout my file with correct line endings.

I work on Windows but I have the same problem in Linux too.

Here is my scenario (Win7 64-Bit):

First I make sure that git converts CRLF to LF on commit and LF to CRLF on checkout:

git config --local core.autocrlf true

Then I create a file called crlf.txt with CRLF line endings and commit it:

git add crlf.txt
git commit -m "File with crlf"

I change something in crlf.txt and commit it:

git add crlf.txt
git commit -m "Change in crlf.txt"

Now I want to get crlf.txt like it was on first commit:

git show HEAD~1:crlf.txt > "/home/user/crlf_like_in_head-1.txt"

The file "crlf_like_in_head-1.txt" contains no CRLF but LF. I think git show is correct because it shows file content like it is in the repository (core.autocrlf=true converts CRLF to LF). I know that from documentation and I tried the same with core.autocrlf=false. With core.autocrlf=false "crlf_like_in_head-1.txt" contains CRLF. I know that I can easily convert LF to CRLF but I have to make sure that the result file is the same like it was checked out with git.

I know I can also checkout a single file with git checkout:

git checkout HEAD~1 crlf.txt

But it overwrites the current content of crlf.txt in the working dir (also if crlf.txt was in a dirty state) and I can't checkout it to a different folder with git checkout.

1 Answers1

1

You got that right – git show just shows you what’s in the repo – no checkout magic going on.

You can achieve what you want by temporarily changing the location of your working directory for your checkout

git --work-tree=/home/user checkout HEAD~1 crlf.txt

This will check out the file to /home/user/crlf.txt. Note: If you checkout out a file in a subdir, that directory will also be created in the target folder. You can not prevent that, nor specify the filename of the target file. If that is a problem you should write a 2-line shell script that does the checkout to a temp dir and then moves the checked out file.

Chronial
  • 66,706
  • 14
  • 93
  • 99
  • Thank you for the reply. But that doesn't work under Win32. It returns the following error: "error: pathspec 'hallo.txt' did not match any file(s) known to git." I also tried it with the core.worktree option. It works if I checkout a full branch or revision (git --work-tree=/home/user checkout HEAD~1) – fernsehkind Dec 08 '12 at 23:32
  • I had the same problem while testing this. Are you trying to check out to a path that’s a parent of your repo? – Chronial Dec 10 '12 at 13:46
  • Yes I did. But I also tried a completly other path. But it doesn't work. – fernsehkind Dec 21 '12 at 14:59
  • Same version of git on Win32 as *nix? I think the pathspec processing got smarter along the way. – qneill Nov 07 '13 at 16:47