2

I have two unrelated repos, A and B. I wish to fetch a specific file from A for a specific commit/hash/tag and copy it into B.

I have both A and B locally, i.e. both a cloned.

Thus far the only method I have is go to A, checkout to the desired commit, go back to B and do a cp path_to_repo_A/file path_to_repo_B/file

1 Answers1

3

You can use git show "[commit/hash/tag]:[file]" in repo A to print the contents of a file from git without checking it out. You can then pass that to a file in repo B.

E.g. to copy README.md on the main branch:

cd A
git show "main:README.md" > ../B/README.md
cd ../B
git add README.md
git commit

You might also find the -C option to git useful - it let's you specify the path for git to work from without having to cd to it:

cd B
git -C ../A show "main:README.md" > README.md
git add README.md
git commit
rjmunro
  • 27,203
  • 20
  • 110
  • 132
  • 1
    This is awesome, thank you very much! Exactly what I'm looking for, but I'll give it some minutes in case something else shows up before I accept <3 – Berthrand Eros Mar 15 '22 at 13:43
  • This method will do what you asked for, but there's nothing 'git' about it. Ie, the history of the origin file is discarded, and future changes to it won't be propagated to your destination file. Instead, check https://stackoverflow.com/a/11593308/7859025 for a method using `git checkout --patch B Their-README.md My-README.md` which gives you the file you want, but also retains its history and future updates. – Jaredo Mills Mar 15 '22 at 22:34