Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preserve line endings when I check out a single file to a different location with git?

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.

like image 439
fernsehkind Avatar asked Nov 13 '22 16:11

fernsehkind


1 Answers

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.

like image 104
Chronial Avatar answered Nov 15 '22 05:11

Chronial